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

后端 未结 21 2074
小蘑菇
小蘑菇 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:47

    I would argue that an expression like

    for ( int i = 0 ; i < 100 ; ++i )
    {
      ...
    }
    

    is more expressive of intent than is

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

    The former clearly calls out that the condition is a test for an exclusive upper bound on a range; the latter is a binary test of an exit condition. And if the body of the loop is non-trivial, it may not apparent that the index is only modified in the for statement itself.

提交回复
热议问题