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

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

    As already said by Ian Newson, you can't reliably loop over a floating variable and exit with !=. For instance,

    for (double x=0; x!=1; x+=0.1) {}
    

    will actually loop forever, because 0.1 can't exactly be represented in floating point, hence the counter narrowly misses 1. With < it terminates.

    (Note however that it's basically undefined behaviour whether you get 0.9999... as the last accepted number – which kind of violates the less-than assumption – or already exit at 1.0000000000000001.)

提交回复
热议问题