enum
is a list of constant signed int
that implicitly starts from 0. Its value must be of literals that could be known at compile time which means that the values should not be a result of a function call or an object evaluation.
The syntax is as follows:
enum constants {
FIRST, // 0
SECOND = 3,
THIRD = 2 * SECOND,
};
In CPP
To enforce type safety in enum
in C++, one could apply the modifier class
to the enum
like the following:
enum class Color { red, green, blue };
By then, we can only access the variable red
with the scope Color
, like Color::red
. This avoids the variable been declared in global scope so that we could declare another variable red
in different scope.