Is there a technical reason to use > (<) instead of != when incrementing by 1 in a 'for' loop?

后端 未结 21 2076
小蘑菇
小蘑菇 2020-12-23 19:48

I almost never see a for loop like this:

for (int i = 0; 5 != i; ++i)
{}

Is there a technical reason to use >

21条回答
  •  情书的邮戳
    2020-12-23 20:34

    There are several ways to write any kind of code (usually), there just happens to be two ways in this case (three if you count <= and >=).

    In this case, people prefer > and < to make sure that even if something unexpected happens in the loop (like a bug), it won't loop infinitely (BAD). Consider the following code, for example.

    for (int i = 1; i != 3; i++) {
        //More Code
        i = 5; //OOPS! MISTAKE!
        //More Code
    }
    

    If we used (i < 3), we would be safe from an infinite loop because it placed a bigger restriction.

    Its really your choice whether you want a mistake in your program to shut the whole thing down or keep functioning with the bug there.

    Hope this helped!

提交回复
热议问题