Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are C++ enums signed or unsigned?

Tags:

c++

enums

Are C++ enums signed or unsigned? And by extension is it safe to validate an input by checking that it is <= your max value, and leave out >= your min value (assuming you started at 0 and incremented by 1)?

like image 588
Matt Avatar asked Oct 01 '08 18:10

Matt


People also ask

Is enum int or Uint C?

In C, each enumeration constant has type int and each enumeration type is compatible with some integer type.

What type are C enums?

Enumeration or Enum in C is a special kind of data type defined by the user. It consists of constant integrals or integers that are given names by a user. The use of enum in C to name the integer values makes the entire program easy to learn, understand, and maintain by the same or even different programmer.

How are enums stored in C?

Enumeration "values" aren't stored at all, as they are compile-time named constants. The compiler simply exchanges the use of an enumeration symbol, with the value of it.

Can enums be unnamed?

They do create distinct new types. (However, the type of an unnamed enumeration does not have a name; its type can be accessed with the keyword decltype or deduced via type deduction.)


1 Answers

Let's go to the source. Here's what the C++03 standard (ISO/IEC 14882:2003) document says in 7.2-5 (Enumeration declarations):

The underlying type of an enumeration is an integral type that can represent all the enumerator values defined in the enumeration. It is implementation-defined which integral type is used as the underlying type for an enumeration except that the underlying type shall not be larger than int unless the value of an enumerator cannot fit in an int or unsigned int.

In short, your compiler gets to choose (obviously, if you have negative numbers for some of your ennumeration values, it'll be signed).

like image 62
Michael Burr Avatar answered Sep 27 '22 15:09

Michael Burr