how does compiler treat for loop checks

Go To


If am doing something like

for i = 0; i < len(arr); i++ {

Is the len() calculated at every iteration ? For gcc is there any optimization flag that can be set to change it.

2012-04-04 17:11
by user361697
There are thousands of compilers, that each could handle this differently. Be more specific - asawyer 2012-04-04 17:14


I believe that the language definition (assuming we're taking C/C++ here) requires that it is invoked every time. As suggested in other answers, you have to do this optimisation yourself. The compiler generally can't know whether calling the len() function will have side effects, or will return the same value on each invocation, so can't generally pull it out of the loop. Since you know what len() does, you can perform that optimisation.

2012-04-04 17:15
by Tom Quarendon
wouldn't it be sufficient to have the final result be such that it is the same as if it had been invoked every time - alvin 2012-04-04 17:31


Yes, len() is invoked at every iteration. It it is the same if you use a simple variable instead.

for( i=0 ; i< a; i++)

While it is not recommended you can change the value of a mid-run.

2012-04-04 17:15
by Andrei


if it does not change during each iteration. it is called a loop invariant. loop invariants can be (can is the word) be hoisted above the loop body. but it is not necessary to do that for correctness. and in the case of a function call, it will be difficult for the compiler to determine if the value is a loop invariant or not. if it were an inline function, then it would be theoretically possible to determine the loop invariance. but i am not sure if any specific compiler actually does this.

see loop invariant code motion for more information

2012-04-04 17:20
by alvin


If you don't want len executed every time:

int length = len(arr);

for i = 0; i < length; i++ {
2012-04-04 17:13
by Paul Nikonowicz
That wasn't the question - NoName 2012-04-04 17:16