user361697
user361697

Reputation: 1131

how does compiler treat for loop checks

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.

Upvotes: 2

Views: 495

Answers (4)

alvin
alvin

Reputation: 1196

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

Upvotes: 1

Tom Quarendon
Tom Quarendon

Reputation: 5716

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.

Upvotes: 2

Andrei
Andrei

Reputation: 287

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.

Upvotes: 1

Paul Nikonowicz
Paul Nikonowicz

Reputation: 3903

If you don't want len executed every time:

int length = len(arr);

for i = 0; i < length; i++ {
    ...
}

Upvotes: 0

Related Questions