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

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

    != would allow the test to evaluate true if the value of i exceeds 10, while < would cause it to evaluate false if i exceeded 10 or merely became equal to it.

    If the value of i might change within the body of the loop, this could be a consideration.

    If, however, you're just looking to do something a set number of times, < is more descriptive, but either would suffice. != should, for simple step-through-10-items-and-do-grunt-work kinds of loops, be considered suboptimal in terms of being explicit about your intent.

提交回复
热议问题