Enum constants behaving differently in C and C++

In C, an enum constant is of type int. In C++, it’s of the enumerated type.

enum en_e{
    en_e_foo,
    en_e_bar=UINT64_MAX,
};

In C, this is a constraint violation, requiring a diagnostic (if UINT64_MAX exceeds INT_MAX, which it very probably does). A C compiler may reject the program altogether, or it may print a warning and then generate an executable whose behavior is undefined. (It’s not 100% clear that a program that violates a constraint necessarily has undefined behavior, but in this case the standard doesn’t say what the behavior is, so that’s still undefined behavior.)

gcc 6.2 doesn’t warn about this. clang does. This is a bug in gcc; it incorrectly inhibits some diagnostic messages when macros from standard headers are used. Thanks to Grzegorz Szpetkowski for locating the bug report: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=71613

In C++, each enumeration type has an underlying type, which is some integer type (not necessarily int). This underlying type must be able to represent all the constant values. So in this case, both en_e_foo and en_e_bar are of type en_e, which must be at least 64 bits wide, even if int is narrower.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)