Re: Strange behavior with for loops in MSVC++2005
On 21 Mai, 21:59, "josef.gr...@gmail.com" <josef.gr...@gmail.com>
wrote:
Hello.
We recently encountered the following strange behavior in Microsoft
Visual Studio 2005 SP1.
//-----------------------
template <typename A> void f();
struct S { friend void f<S>(); };
template <typename A> void f() {}
void test() {
for (int i = 0;;) {}
i = 123; // This line does not generate an error!}
//-----------------------
By including the first three lines, the compiler suddenly starts to
leak loop variables out of for loop scopes. As far as we can tell, it
seems to work appropriately in all other respects. If the first three
lines are removed or permutated, the compiler generates an error as
one should expect.
Is this a known problem, and what workarounds might there be?
Part of your problem is "old evil" of the MS compiler family. Due
to backwards-compatibility the above code compiles undiagnosed in
a configuration with enabled extensions (/Ze or lack of /Za in the
command line) but with explicit /Zc:forScope- (which is *not* part
of the standard configuration!).
If you do not need the extension mode, you could switch to
/Za mode (Disable Language Extensions: Yes). This does not work
well with <windows.h> and his friends.
The second part of your problem (i.e. working under /Ze) seems
indeed to be a compiler error related to your template code, as
I just can confirm. Interestingly the compiler behaves as if it
had silently switched to /Zc:forScope- mode. You can see this,
if you set the warning level to W4. Then the compiler diagnoses:
"warning C4702: unreachable code"
which it also does, if the template code is commented and you
combine /Zc:forScope- with /Ze.
(Funnily it seems not possible to combine /Za with /Zc:forScope-,
the compiler will always ignore the /Zc:forScope- value).
Currently I have no good idea as a workaround (except to switch
to /Za mode, but that might be infeasible for you).
Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]