Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function call in for loop condition?

Tags:

c++

c++11

If I have function call in for loop condition like this:

for (auto it = s.begin(); it != s.end(), ++it) {}

is it called on each iteration? I expect that yes. Is compiler allow to optimized it away? Are current compilers smart enough to do so? Or am I better using something like following:

for (auto it = s.begin(), auto end = s.end(); it != end; ++it) {}

?

like image 884
graywolf Avatar asked Oct 19 '15 15:10

graywolf


People also ask

Can you call functions in a for loop?

A Python for loop is used to loop through an iterable object (like a list, tuple, set, etc.) and perform the same action for each entry. We can call a function from inside of for loop.

Can we use == conditions in for loop?

Solution: for(;;) is the same as while(true). What's wrong with the following loop? The while loop condition uses = instead of == so it is an assignment statement (which makes done always false and the body of the loop will never be executed). It's better to style to avoid using ==.


1 Answers

In

for ( auto it = s.begin(); it != s.end(), ++it )

s.begin() is called only once.
s.end() and operator++() (for ++it) are called in each iteration of the loop.

Is compiler allow to optimized it away?

The compiler can optimize away the call to s.end() depending on the compiler, the implementation, and the optimization level. I will be surprised if it can optimize away the operator++() call.

Are current compilers smart enough to do so?

Can't answer that.

Or am I better using something like following:

for (auto it = s.begin(), auto end = s.end(); it != end; ++it) {}

It won't hurt. However, it can be a problem if s is modified in the loop. If s is not modified in the loop, I would recommend using this approach.

like image 99
R Sahu Avatar answered Oct 10 '22 03:10

R Sahu