简体   繁体   中英

integer constant is so large that it is unsigned when assigning max type value to enum

Here is my enum declaration :

enum connection_primary_identifier_e : uint64_t
{
    INVALID_IDENTIFIER = std::numeric_limits<std::underlying_type<connection_primary_identifier_e>::type>::max(),
}

(same happens if I use uint64_t directly as the type, also if I use -1 or -1ULL )

When I try to compile the file I get the following errors / warnings :

error: integer constant is so large that it is unsigned [-Werror]
error: narrowing conversion of ‘18446744073709551615I128’ from ‘__int128’ to ‘unsigned int’ inside { } [-Werror=narrowing]
error: large integer implicitly truncated to unsigned type [-Werror=overflow]
cc1plus: all warnings being treated as errors

The really weird thing is, the errors are actually produced for non-existing lines (line number is 3 after the last line on file) on another file (which uses the enum), I made sure it isn't a missing parentheses or anything like that.

Update: Using uint32_t doesn't produce the error.

Using g++ (GCC) 4.8.3

Might be because std::underlying_type was initially underspecified and didn't require a complete type. This unintentionally allowed precisely this code, which uses connection_primary_identifier_e while it's still incomplete.

Starting with C++17, your code is definitely illegal.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM