简体   繁体   中英

Evaluation of Conditional Expression in for loop

I have a query:

Suppose I have the following code:

Code A:

for (int i = 0; i < n + 1; i++)
{
  // something here
}

Code B:

int lim = n + 1;
for (int i = 0; i < lim; i++)
{
   // something here
}

Which code will be more efficient? Does the conditional expression in Code A gets computed in each iteration of the for loop or does modern compilers take care of it and themselves assign it a constant value?

This depends on many factors. This kind of an optimization is legal if the compiler can prove that the value of n does not change for the duration of the loop. If n , for example, is a variable in global or dynamic scope and there's a function call in the middle of the loop, the compiler cannot generally assume that whatever the function gets called will not modify the globally or dynamically-scoped variable. Otherwise the two versions of the loop will not, obviously, be the same.

Or, even if the variable is in local or automatic scope, and there's a pointer somewhere in the vicinity, it may or may not be possible for it to be modified through a pointer, so this optimization will not be safe either.

The compiler is permitted to make optimization-related code changes only if the compiler can prove that there are no observable change from the optimization. And finally, if the compiler can prove that there will not be any observable changes from the optimization, whether or not the compiler will implement this may depend on the compilation options.

It depends.

If n is modified inside the loop, then the compiler can't optimize and the condition needs to evaluate n+1 first. If n is not modified, the compiler could assign a constant value to the upper bound of i . Both in A and in B, the compiler will check if the variable which the upper bound depends on, will be modified inside the loop.

Code B allows you to modify the n variable inside the loop without affecting the number of iterations the loop will have.

It really depends on which compiler you are using, the level of optimization it is using, and whether the compiler can reliably tell if the value of n remains constant during each iteration of the loop. Personally, I'd go with B .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM