for (int i = 0; i < foo + bar; ++i)
{
// do something
}
Suppose that foo + bar
is a huge number and that its value does not change during the loop iterations. (That is, the loop's body doesn't alter foo
or bar
)
Does the value of foo + bar
get cached somewhere? Or does it get re-evaluated everytime?
Would C/C++ handle it differently from higher level languages, such as Java?
The C++ language specification does not require any specific optimizations from a particular compiler implementation.
Having said that, if your compiler can figure out that the result of this additionl is invariant, it will likely do that.
Whether or not your C++ compiler is capable of this optimization, of course, depends your compiler. You can examine the resulting object code, using your platform's disassembler, to determine how your code was compiled, and figure out the answer yourself.
If you would like to be certain that this kind of optimization takes place, you are free to "help" your compiler by doing this yourself, by making the appropriate changes to the code.