Home > Software engineering >  Can an enum class variable take the full range of integer values?
Can an enum class variable take the full range of integer values?

Time:10-21

Sometimes it happens that you want to give names to some integer values, but allow for other values than the named ones. In C , this is easily achieved with an ordinary enum:

enum { red, green, blue };
int color = 999;

Suppose in some unusual context, you want to use enum class for type checking, but also allow for other values:

enum class color_t { red, green, blue };
color_t color = (color_t)999;

Is this still okay? Or is it the case that, for example, the compiler could choose to base color_t on char rather than int, which would make 999 not a valid value for the base type? If the latter, can this problem be solved by explicitly declaring the base type with enum class color_t: int?

CodePudding user response:

Enum classes by default will be int, if you want char you can do:

enum class color_t : char { red, green, blue };

CodePudding user response:

[dcl.enum]

8 For an enumeration whose underlying type is fixed, the values of the enumeration are the values of the underlying type.

Once the underlying type is fixed, any value in its range is a value of the enumeration. The enumerators are just named constants in that range.

There is some minutiae involved in determining when the underlying type is fixed, but it doesn't apply here. A scoped enumeration always has a fixed type (int if none is given explicitly).

  • Related