mageta
mageta

Reputation: 687

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

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).

Upvotes: 29

Views: 28673

Answers (2)

Puppy
Puppy

Reputation: 146940

In C++11 you can use an enum class, where you can specify the underlying type. In C++03 there is no solution.

Upvotes: 4

John Calsbeek
John Calsbeek

Reputation: 36497

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.

Upvotes: 63

Related Questions