User account creation filtered due to spam.
If I cast an int to the enum type all values outside the enum triggers the first case-statement.
The number of enum values is important. It must be a power of 2.
This works in GCC 4.3.4.
Created attachment 18622 [details]
g++ case.cpp is sufficient to reproduce this.
As far as I can see, you are triggering undefined behavior. Per 5.2.9/7: "A value of integral or enumeration type can be explicitly converted to an enumeration type. The value is unchanged if the original value is within the range of the enumeration values (7.2). Otherwise, the resulting enumeration value is unspecified."
In C++ an enum type only has the minimum number of bits that is required to
store all its values, thus 1 in your case. So (foo)5 is a truncation.
Paolo, but std::cout << static_cast<foo>(i); prints 5, so it's not the conversion but the switch statement which is "broken".
Richard, if it's only truncation shouldn't case B be triggered?
Switch assembly is optimized if you handle all valid cases (which you do) into
if (i != 0)
(In reply to comment #3)
> As far as I can see, you are triggering undefined behavior.
There is a big difference between undefined and unspecified behaviour. With unspecified behaviour the implementation must chose a consistent behaviour, although it does not have to document which one it choses.
Agreed, unspecified, as the actual citation says.
So it's ok to change the behavior in a minor release?
Yes, as part of a wrong-code fix.
In G++ 4.6 the confusing optimization will only be performed with -fstrict-enums.