On 25.02.2017 05:37, Stefan Ram wrote:
> "Alf P. Steinbach" <
alf.p.stein...@gmail.com> writes:
>> It also occurred to me that I don't know that standard's rules that make
>> this case work as unexpected, but makes the code invalid when the `if`
>> is replaced with a `while` or `switch`.
>
> By »invalid«, you might mean that »seven!« will /not/ be
> printed in the case of a »while«. I believe that the
> standard requires the »while« to behave like the »if«,
> and when »seven!« is not printed, it's an error in the
> C++ implementation.
>
> A nested »switch«, however, clearly starts a new scope
> for case-lables, so it is correct, when »seven!« is not
> printed in this case.
>
Oh, it seems you're right. It looks like a compiler bug. With g++
replacing `if` with `while` makes the "seven!" output disappear:
[example]
[C:\my\temp]
> type undead.cpp
#include <iostream>
using namespace std;
auto main() -> int
{
int const n = 7;
switch( n )
{
case 1: cout << "one!\n"; break;
while( false )
{
case 7: cout << "seven!\n"; break;
}
default: cout << "Switch default.\n";
}
}
[C:\my\temp]
> (g++ --version | find "++") && g++ undead.cpp && a
g++ (x86_64-win32-sjlj-rev1, Built by MinGW-W64 project) 6.3.0
Switch default.
[C:\my\temp]
> _
[/example]
With Visual C++ 2015 it's executed:
[example]
[C:\my\temp]
> (cl /nologo- 2>&1 | find "++") && cl undead.cpp /Feb && b
Microsoft (R) C/C++ Optimizing Compiler Version 19.00.23725 for x86
undead.cpp
seven!
Switch default.
[C:\my\temp]
> _
[/example]
Still, with the compilers disagreeing it would be nice to know what the
standard says about this. I guess C++ /should/ behave like old C here
for backward compatibility, e.g. in order to make the old Duff's device
trick work. So it seems Visual C++ is right and g++ is buggy, but... :)
Cheers!,
- Alf