In C++, an enumeration (enum
) is a special data type that represents a set of constant values. It allows for better readability when working with predefined categories or states.
Defining an Enum
To create an enum. use the enum keyword followed by its name and a list of constants inside curly braces {}
.
Example: Declaring an Enum
enum EngineState { OFF, IDLE, RUNNING };
This enum groups three constant values:
OFF
(default value0
)IDLE
(default value1
)RUNNING
(default value2
)
Using an Enum
To work with an enum, declare a variable of its type.
Example: Assigning and Printing Enum Values
#include <iostream> using namespace std; int main() { // Create an enum variable and assign a value enum EngineState engineStatus = IDLE; cout << engineStatus; // Outputs: 1 return 0; }
Since IDLE
is the second item, its default value is 1.
Customizing Enum Values
By default, enums start at 0
and increment by 1
, but you can assign custom values.
Example: Custom Enum Values
enum EngineState { OFF = 10, IDLE = 20, RUNNING = 30 }; int main() { EngineState engineStatus = IDLE; cout << engineStatus; // Outputs: 20 return 0; }
Custom values help improve clarity in programs.
Automatic Value Increment
If you set a value for one item, the next ones automatically increase.
Example
enum EngineState { OFF = 100, IDLE, // 101 RUNNING // 102 };
Using Enum in a switch Statement
Enums are often used in switch
cases for structured decision-making.
Example: Evaluating Engine Status
#include <iostream> using namespace std; enum EngineState { OFF = 0, IDLE, RUNNING }; int main() { EngineState engineStatus = RUNNING; switch (engineStatus) { case OFF: cout << "Engine is OFF."; break; case IDLE: cout << "Engine is IDLING."; break; case RUNNING: cout << "Engine is RUNNING."; break; } return 0; }