In a “for” statement, should I use `!=` or `<`?

后端 未结 8 775
悲&欢浪女
悲&欢浪女 2021-02-02 05:39

I\'ve seen both of these two for statements:

for(i=0;i<10;i++) 

for(i=0;i!=10;i++)

I know they all stop when i reaches 10 , bu

8条回答
  •  暖寄归人
    2021-02-02 06:12

    I usually use < in for-loops for the reasons stated by others. In while-loops and more advanced for-loops though, != makes it much easier to reason about what my program does.

    Say I want to find the position after the first run of '5's in an array like [5,5,5,3,5,2,3,2,0]. That is we want k such that 0 <= i < k => a[i] = 5:

    int pos = 0;
    // Inv: a[0..pos) = 5
    while (pos != N && a[pos] == 5)
        pos = pos+1;
    

    Once the loop has executed we know that the inverse of the loop guard is true: pos == N || a[pos] != 5. In either case we have the pos we want.

    Now say we had used < in the loop guard, then all we would have known afterwards was pos >= N || a[pos] != 5, but that's not the situation we wanted to be in. Doing a lot more work, we can prove that we can't possible be in pos > N, but that seams like a waste of time compared to just using != in the loop guard.

提交回复
热议问题