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.
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.
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.
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
If you don't want len executed every time:
int length = len(arr);
for i = 0; i < length; i++ {
...
}