Search code examples
c++loopsoptimizationas-if

Evaluation of constants in for loop condition


for(int i = 0; i < my_function(MY_CONSTANT); ++i){
    //code using i
}

In this example, will my_function(MY_CONSTANT) be evaluated at each iteration, or will it be stored automatically? Would this depend on the optimization flags used?


Solution

  • It has to work as if the function is called each time.

    However, if the compiler can prove that the function result will be the same each time, it can optimize under the “as if” rule.

    E.g. this usually happens with calls to .end() for standard containers.


    General advice: when in doubt about whether to micro-optimize a piece of code,

    1. Don't do it.
    2. If you're still thinking of doing it, measure.
    3. Well there was a third point but I've forgetting, maybe it was, still wait.

    In other words, decide whether to use a variable based on how clear the code then is, not on imagined performance.