C++ Enum Switch Case Example
Enums (enumerations) in C++ provide a way to define a set of named integer constants. This makes your code more readable and easier to maintain. The switch
statement allows you to execute different blocks of code based on the value of a variable. This article will demonstrate how to use enums and switch statements together in C++.
Example Code
#include
// Define an enum called Color
enum Color {
RED,
GREEN,
BLUE
};
int main() {
// Declare a variable of type Color and assign it a value
Color userColor = BLUE;
// Use a switch statement to handle different colors
switch (userColor) {
case RED:
std::cout << "The color is red" << std::endl;
break;
case GREEN:
std::cout << "The color is green" << std::endl;
break;
case BLUE:
std::cout << "The color is blue" << std::endl;
break;
default:
std::cout << "Invalid color!" << std::endl;
}
return 0;
}
Explanation
- Enum Declaration: The
enum Color
declaration defines an enumeration calledColor
with three constants:RED
,GREEN
, andBLUE
. By default, these constants have values 0, 1, and 2 respectively. - Variable Declaration: A variable
userColor
of typeColor
is declared and assigned the valueBLUE
. - Switch Statement: The
switch
statement evaluates the value ofuserColor
. - Case Statements: Each
case
statement checks if the value ofuserColor
matches the constant defined in thecase
. If a match is found, the corresponding code block is executed. - Break Statement: The
break
statement is used to exit theswitch
statement after a match is found. This prevents the execution of subsequentcase
statements. - Default Statement: The
default
statement is optional. It is executed if none of thecase
statements match the value of the variable.
Output
The above code will produce the following output:
The color is blue
Advantages of Using Enums and Switch Statements
- Readability: Enums improve code readability by replacing magic numbers with descriptive names.
- Maintainability: When you need to change the value of a constant, you only need to modify it in the enum definition, not throughout your code.
- Error Prevention: Switch statements enforce a clear and structured approach to handling different values, reducing the risk of errors.
Conclusion
Combining enums and switch statements in C++ provides a powerful and efficient way to manage and handle different values in your code. This approach makes your code cleaner, more readable, and less error-prone.