Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I define the size of an enum in c++?

Tags:

From what I know (from what I read in the cpp-programming-language) the size would be the size of "some integral type that can hold its range and not larger than sizeof(int), unless an enumerator cannot be represented as an int or as an unsigned int".

But is it possible to define the size in some way? For example, I would like to use an enum whose sizeof is the size of the natural word (usually unsigned long).

like image 515
mageta Avatar asked Aug 25 '12 21:08

mageta


People also ask

Why is enum size 4?

The size is four bytes because the enum is stored as an int . With only 12 values, you really only need 4 bits, but 32 bit machines process 32 bit quantities more efficiently than smaller quantities.

How do you define enum value?

An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.

Can we change value of enum in C?

You can change default values of enum elements during declaration (if necessary).


1 Answers

You can in C++11:

enum /*class*/ MyEnum : unsigned long {     Val1,     Val2 }; 

(You can specify the size of an enum either for the old-style enum or the new-style enum class.)

You can also increase the minimum size of an enum by fun trickery, taking advantage of the last phrase of the sentence that you cited:

enum MyEnum {     Val1,     Val2,     ForceSize = 0xFFFFFFFF // do not use }; 

…which will ensure that the enum is at least 32-bit.

like image 65
John Calsbeek Avatar answered Oct 19 '22 14:10

John Calsbeek