c++ for loop temporary variable use
c++, for-loop
Solution
Example (b) has a different meaning to example (a), and the compiler must interpret it as you write it.
If, (for some made-up reason that I can't think of), I wrote code to do this:
for( int i(0);i < vec.length(); ++i)
{
if(i%4 == 0)
vec.push_back(Widget());
}
I really would not have wanted the compiler to optimise out each call to vec.length(), because I would get different results.
Problem
Which of the following is better and why? (Particular to c++) a. ``` int i(0), iMax(vec.length());//vec is a container, say std::vector for(;i < iMax; ++i) { //loop body } ``` b. ``` for( int i(0);i < vec.length(); ++i) { //loop body } ``` I have seen advice for (a) because of the call to length function. This is bothering me. Doesn't any modern compiler do the optimization of (b) to be similar to (a)?