Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 , but it seems better to use the second one (I heard). What is the different?I also want to know when use iterator to access member of a vector, what is the difference between iterator condition < vec.end()and != vec.end()

like image 790
Archeosudoerus Avatar asked Nov 18 '11 06:11

Archeosudoerus


People also ask

Which expressions are optional in a for loop?

All three expressions in the head of the for loop are optional. Like the initialization block, the condition block is also optional. If you are omitting this expression, you must make sure to break the loop in the body in order to not create an infinite loop. You can also omit all three blocks.

What are three expressions used to set up the for loop?

Traditional for-loops Another form was popularized by the C programming language. It requires 3 parts: the initialization (loop variant), the condition, and the advancement to the next iteration.

Is writing all the three expressions related to a for loop mandatory?

All these components are optional. In fact, to write an infinite loop, you omit all three expressions: for ( ; ; ) { //infinite loop ... }

What is meant by for loop?

What Does For Loop Mean? For loop is a programming language conditional iterative statement which is used to check for certain conditions and then repeatedly execute a block of code as long as those conditions are met.


1 Answers

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 <.

like image 191
Brendan Long Avatar answered Oct 01 '22 13:10

Brendan Long