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

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

    for ( initialization ; termination condition ; iteration )

    For each of those , choose youself the best one to fit your requirements, for termination condition you can use any of the binary conditional operators such as > ,< ,>= ,<= ,!=

    For your given question , consider a random case in which,

    for(i=0;i!=10;i++)
    {
     .
     .
     i=11; //somewhere if the loop variable is changed to a value greater than 10 (this assumption is solely for demo)
     .
     .
     .
    }
    

    In this case, the loop turns out to be infinite. rather if you use a condition i<10, this works as usual. so my point is that the first approach is a bit more safer to set condition strictly.

提交回复
热议问题