PapaDiHatti
PapaDiHatti

Reputation: 1921

enum underlying type vs normal type

If i try to compile below code it will give me error that 'enumerator value too large for underlying type 'char'

enum class Status:char{one=126,two=127,three=128};
Status s = Status::three;

However if i execute following code compiler don't give me any errors and silently ignores that char upper range is crossed

char x = 128;

So is there any specific reason why compiler don't check in case of normal data type and check for range in case of enum underlying type.

Upvotes: 1

Views: 272

Answers (1)

kfsone
kfsone

Reputation: 24249

C++11 introduced restrictions on "narrowing conversions" and where they are and aren't allowed. Tucked away in 5.19§3 is a clause that describes "converted constant expression"s and specifically precludes narrowing conversions, and then notes that such expressions may be used in [...] enumerator initializers. Thus, you can't do:

enum class Foo : char { one = 128 };
unsigned char uc1 = {-1};

but you can do

enum class Foo : char { one = (char)128 };
unsigned char uc1 = -1;

5.19 [expr.const] §3

[...] A converted constant expression of type T is an expression, implicitly converted to a prvalue of type T, where the converted expression is a core constant expression and the implicit conversion sequence contains only user-defined conversions, lvalue-torvalue conversions (4.1), integral promotions (4.5), and integral conversions (4.7) other than narrowing conversions (8.5.4). [ Note: such expressions may be used in new expressions (5.3.4), as case expressions (6.4.2), as enumerator initializers if the underlying type is fixed (7.2), as array bounds (8.3.4), and as integral or enumeration non-type template arguments (14.3). —end note ]

Upvotes: 2

Related Questions