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

后端 未结 8 749
悲&欢浪女
悲&欢浪女 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:16

    for(i = start; i != end; ++i)
    

    This is the "standard" iterator loop. It has the advantage that it works with both pointers and standard library iterators (you can't rely on iterators having operator< defined).

    for(i = start; i < end; ++i)
    

    This won't work with standard library iterators (unless they have operator< defined), but it does have the advantage that if you go past end for some reason, it will still stop, so it's slightly safer. I was taught to use this when iterating over integers, but I don't know if it's actually considered "best practice".

    The way I generally write these is to prefer <.

提交回复
热议问题