C or C++ : for loop variable

You can find out, when you look at the generated code

g++ -S file.cpp

and

g++ -O2 -S file.cpp

Look at the output file.s and compare the two versions. If someArray[a+b] can be reduced to a constant value for all loop cycles, the optimizer will usually do so and pull it out into a temporary variable or register.


It will behave as if it was computed each time. If the compiler is optimising and is capable of proving that the result does not change, it is allowed to move the computation out of the loop. Otherwise, it will be recomputed each time.

If you're certain the result is constant, and speed is important, use a variable to cache it.

Tags:

C++

C

For Loop