When I was reading Code Complete 2nd Edition, there was a piece of code:
for ( int recordCount = 0; recordCount < MAX_RECORDS; recordCount++ ) {
// looping code that uses recordCount
}
// intervening code
for ( int recordCount = 0; recordCount < MAX_RECORDS; recordCount++ ) {
// additional looping code that uses a different recordCount
}
The author claimed that he found 3 different C++ compilers that has 3 different behaviors on this:
When I checked this functionality with three different C++ compilers, however, I got three different results:
- The first compiler flagged recordCount in the second for loop for multiple variable declarations and generated an error.
- The second compiler accepted recordCount in the second for loop but allowed it to be used outside the first for loop.
- The third compiler allowed both usages of recordCount and did not allow either one to be used outside the for loop in which it was declared.
As is often the case with more esoteric language features, compiler implementations can vary.
This paragraph bothered me so much because I've always believed that the behavior in the third compiler is the only correct behavior, regarding to the C++ specification.
Can anyone help me to find out which section of the C++ specification specifies this behavior?