C++ Migration Guide

for-Statement Variables

The ARM rules stated that a variable declared in the header of a for-statement was inserted into the scope containing the for-statement. The C++ committee felt that this rule was incorrect, and that the variable's scope should end at the end of the for-statement. (In addition, the rule didn't cover some common cases and, as a result, some code worked differently with different compilers.) The C++ committee changed the rule accordingly. Many compilers, C++ 4.2 included, continued to use the old rule.

In the following example, the if-statement is valid under the old rules, but invalid under the new rules, because k has gone out of scope.


for( int k = 0; k < 10; ++k ) {
    ...
}
if( k == 10 ) ...       // Is this code OK?

In compatibility mode, the C++ 5.0 compiler uses the old rule by default. You can instruct the compiler to use the new rule with the -features=localfor compiler option.

In standard mode, the C++ 5.0 compiler uses the new rule by default. You can instruct the compiler to use the old rule with the -features=no%localfor compiler option.

You can write code that works properly with all compilers in any mode by pulling the declaration out of the for-statement header, as shown in the following example.


int k;
for( k = 0; k < 10; ++k ) {
    ...
}
if( k == 10 ) ...      // Always OK