Loop condition: why “not-equal” instead of “lower-than”

后端 未结 5 1937
攒了一身酷
攒了一身酷 2021-01-04 08:56

I was assigned to work on an Android-Java (real-time game) project with a considerable (partially legacy) code base.

Most of the loops I see are like this (where mjk

5条回答
  •  不知归路
    2021-01-04 09:37

    If the loop variable i somehow gets an incorrect, out-of-range value inside the loop, the first version will crash, and the second version will just end the loop.

    This can be an advantage for the first version, the one that crashes. When your bank runs programs to handle your money, and there is an error, do you wish the program to crash with an obvious error, so they know that they have to fix it, or should it just silently go on and compute an incorrect result?

    There are of course systems (life support, aircraft control, etcetera) where any result would be better than a stopped program. But it would be unwise to assume that as a general rule.

提交回复
热议问题