![]() |
VOOZH | about |
In C++, enumeration is a user-defined data type that consists of a set of named integer constants.
1
An enum needs to be defined before we can create its variables.
where name1, name2, .... are the names for the constant. They should be unique identifiers. By default, the first name in an enum is assigned the integer value 0, and the subsequent ones are incremented by 1.
After that, we can create a variable of this enum and assign it some name constant that was defined in it.
We can manually assign values to enum members if needed.
val1, val2 ... values should be integer. It is also not compulsory to define the value of all constant names. If the current constant name value is x, then subsequent values will keep incrementing by one.
5 6
C++11 introduced enum class, which provides better type safety. It helps in resolving name conflicts by providing scope to the constant names. It also requires explicit typecasting to convert enum values to integers.
Enum class can be created just by adding the class keyword in the enum declaration.
5
If we try to just assign the name of the constant to the enum variable, compiler gives an error.
Output
main.cpp: In function ‘int main()’:
main.cpp:12:17: error: ‘Thursday’ was not declared in this scope; did you mean ‘Day::Thursday’?
12 | Day today = Thursday;
| ^~~~~~~~
| Day::Thursday
main.cpp:6:28: note: ‘Day::Thursday’ declared here
6 | Wednesday, Thursday, Friday,
| ^~~~~~~~