Search code examples
c++for-loopoptimizationcompiler-optimizationloop-invariant

Is the condition of a loop re-evaluated each iteration?


I have a loop that looks like this:

for (int i = 0; i < dim * dim; i++)

Is the condition in a for loop re-evaluated on every loop?

If so, would it be more efficient to do something like this?:

int dimSquare = dim * dim;
for (int i = 0; i < dimSquare; i++)

Solution

  • In general, if you would for example change the value of "dim" inside your loop, it would be re-evaluated every time. But since that is not the case in your example, a decent compiler would optimize your code and you wouldn't see any difference in performance.