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) {}
?
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.
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 ==.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With