Ill-formed program with a fixed enumeration instead of overflow

Viewed 68

In the following declaration:

enum class en : signed char { A = 127, B };

gcc (and clang) says that the B value is outside the range of the enumeration, which is [-128, 127]. An error is also shown when writting:

enum class en : signed char { A = 128 };

However, in the second case, the initializer must be a converted constant expression from type int to type signed char, which disallows narrowing conversion and thus that construct is ill-formed.

But what about the first case? There's no initializer so that rule doesn't apply.

The standard says:

[dcl.enum]§2 An enumerator-definition without an initializer gives the enumerator the value obtained by increasing the value of the previous enumerator by one.

So, it's obvious that the choosen range (signed char) is not big enough to save the value 128.

Maybe compilers decide to treat that case as a rule violation (and thus the program is ill-formed), but I don't see that as a rule violation, because it's not some kind of property of the program that violates a rule, but a command about what the compiler shall do. In this case, I would say it is a corner case not explicitely described or forbidden.

0 Answers
Related