Hassen Dhia Hassen Dhia - 1 year ago 46
C Question

Would the compiler optimize this for loop?

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

loop in which a counter is counting from
, and
is a variable (not a function call, and NOT A CONSTANT either), would the compiler optimize the loop by checking if the variable
(the bound variable) will be changed during the loop (accessed for write, eg:
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 Source

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

    while ( condition ) {
    expression ;