Hassen Dhia Hassen Dhia - 2 months ago 8
C Question

Would the compiler optimize this for loop?

In C or C++, if the compiler encounters a

for
loop in which a counter is counting from
0
to
n
, and
n
is a variable (not a function call, and NOT A CONSTANT either), would the compiler optimize the loop by checking if the variable
n
(the bound variable) will be changed during the loop (accessed for write, eg:
n
can be a length of a string that is calculated before the loop), by optimizing here I mean copying its value to a register to avoid memory access?

Here is an example:

for (int c = 0; c < n; c++) {
// do something not related to n
}


would the compiler notice that and optimize it?

Answer

Yes, at least GCC and most other compilers will do this. If you attempt to see what the for loop variable is, the debugger says that the variable has been optimized out, when you compile with -O1 or higher. Of course the compiler is not required to do this. This is what the standard says.

The for statement

for ( for-init-statement conditionopt; expressionopt) statement

is equivalent to

{
for-init-statement
    while ( condition ) {
    statement
    expression ;
    }
}
Comments