View Full Version : C++: declaration inside for()
WarpEnterprises
19th September 2003, 07:48
It seems common (e.g.in linux) to use code like
for (int y = 0x700; y <= 0x7ff; ++y)
compmap[y] = (y - 0x600) << 6;
for (int y = 0x600; y <= 0x6ff; ++y)
compmap[y] = (y - 0x500) << 5;
while MS VC complains that int y is declared twice here.
Who knows which is true?
Is the scope of y the loop body or the body where the FOR statement is in?
Nic
19th September 2003, 08:57
It is a weird one. In VC 7 (and higher) it is allowed. So y gets the scope of the whole function rather than just the loop. (that's even true in VC7 I believe, but there it just allows the second declaration without complaining)
I think that's right ;)
-Nic
fu2k
19th September 2003, 12:39
In an early C++ draft standard, the scope of variables defined in a "for" statement as you have shown, extended beyond the statement into the enclosing block. This allowed (for example) a loop counter to be checked outside the loop to see if the loop terminated normally or due to a "break" statement.
But before C++ was standardised, the scope was changed to be inside the "for" loop only.
Unfortunately, MS VC 6 and earlier uses the "old" standard. This means that it will complain about the code snippet you showed, because it sees y defined twice.
MS VC 7 and later use a strange hybrid approach, that allows a definition in a "for" loop to weakly propagate to the enclosing scope. If there is another definition of the same identifier in the enclosing scope then the inner identifier is "hidden". This allows legacy code that requires the old semantics, and conforming code to both compile.
gabest
19th September 2003, 23:50
This reminds me an interesting bug in vc7. When the declared variable was a class and usage after the loop was allowed in the project settings, the compiler still inserted the destructor call there, right after the for loop :D
In vc71 they fixed it with an "undeclared identifier" compiler error when you try to reuse your variable. With simple types it still works.
vBulletin® v3.8.11, Copyright ©2000-2026, vBulletin Solutions Inc.