You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
An enum (short for "enumeration") is a user-defined type that consists of
a set of named integral constants, providing a way to define a
collection of related constants with meaningful names.
Enumerations improve code readability by replacing numeric values with
descriptive names.
Usage
Represent some states with integers by using an enum to group and
represent them.
Unscoped Enumeration Syntax
enum EnumName {
MEM1, // 0
MEM2, // 1
...,
MEMN = n, // n
MEMN1, // n + 1
...
};
EnumName enum_name = MEM2;
Scoped Enumeration Syntax
enum EnumName : Type {
MEM1, // 0
MEM2, // 1
...,
MEMN = n, // n
MEMN1 // n + 1
...
};
EnumName enum_name = EnumName::MEM2;
Unscoped Enumeration Syntax with a Scope
Class ClassName {
enum EnumName {
MEM1, // 0
MEM2, // 1
...,
MEMN = n, // n
MEMN1, // n + 1
...
};
};
EnumName enum_name = ClassName::MEM2;
Differences Between enum (Unscoped Enumeration) and enum class (Scoped Enumeration)
Syntax
Namespace Scoping
enum: Enum values injected into enclosing scope.
enum class: Enum values scoped within the enum type.
Type Safety
enum: Implicitly converts to int.
enum class: No implicit conversions.
Underlying Type
enum: Cannot specify underlying type explicitly.
enum class: Can specify underlying type (e.g.,
enum class Color : unsigned int).
Forward Declaration
enum: Not allowed.
enum class: Allowed.
Bitwise Operations
enum: Allowed without extra effort.
enum class: Not allowed without operator overloading.