Enums
Published Aug 3, 2021Updated Apr 24, 2023
Contribute to Docs
In C++, an enumeration (enum) is a user defined type where a set of values is specified for a variable and the variable can only take one out of a small set of possible values.
Syntax
The keyword enum
is used to define an enumeration.
enum name {const1, const2, ...};
Here’s an example:
enum day {sun, mon, tue, wed, thu, fri, sat};
sun
would have the value 0mon
would have the value 1tue
would have the value 2wed
would have the value 3thu
would have the value 4fri
would have the value 5sat
would have the value 6
Here’s another example where one of the constants is assigned a value:
enum grade {freshman=9, sophomore, junior, senior};
The enumerator freshman
is assigned the value 9
. Subsequent enumerators, if they are not given an explicit value, receive the value of the previous enumerator plus one.
So here:
freshman
would have the value 9sophomore
would have the value 10junior
would have the value 11senior
would have the value 12
Codebyte Example
Scoped Enums
Scoped enums are a feature added in C++11.
Scoped enums differ from unscoped enums by:
- Containing their constants in their namespace.
- Being strongly-typed.
- By containing their constants to their namespace, scoped enumerations avoid name conflicts with other enumerations.
Example
enum class WeekDay {sun, mon, tue, wed, thu, fri, sat};WeekDay day = WeekDay::sun; // Notice that "sun" is prefaced with "Weekday::"int friday = WeekDay::fri; // error, must cast to an int
Here’s an example where scoped enumerations avoid name collisions:
enum class LogResult {Success, InvalidFileName, WriteError};enum class SocketResult {Success, InvalidAddrError, TimeoutError};LogResult logger_result = LogResult::Success;if (logger_result == LogResult::Success) {} // Because Success is scoped to LogResult, it doesn't collide with SocketResult::Success
All contributors
Looking to contribute?
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.