Enums in C++
Enums, short for enumerations, are a way to define a set of named values in C++. They provide a convenient and readable way to represent a fixed set of values as constants. Enums are especially useful when you have a limited number of possible values that a variable can take. In this lesson, we'll explore how to define and use enums in C++.
Enum Declaration and Values
In C++, you can declare an enum using the
enum
keyword, followed by the name of the enum and the list of possible values enclosed in curly braces. Each value in the enum is assigned an integer constant, starting from 0 by default. However, you can assign specific values to the enum constants if desired.
enum Color {
RED, // Assigned the value 0
GREEN, // Assigned the value 1
BLUE // Assigned the value 2
};
enum Days {
MON = 1, // Assigned the value 1
TUE, // Assigned the value 2
WED, // Assigned the value 3
THU, // Assigned the value 4
FRI, // Assigned the value 5
SAT, // Assigned the value 6
SUN // Assigned the value 7
};
Using Enums
Once you have defined an enum, you can use it to declare variables and assign values from the enum. The values of an enum can be accessed using the enum constants as if they were variables.
#include <iostream>
int main() {
Color myColor = GREEN;
std::cout << "Selected color: " << myColor << std::endl;
Days today = TUE;
std::cout << "Today is day: " << today << std::endl;
return 0;
}
Enums with Functions
Enums are often used in functions to define parameters or return types that have a limited set of possible values. Functions can take enum values as arguments or return enum values to indicate different states or options.
#include <iostream>
enum MathOperation {
ADDITION,
SUBTRACTION,
MULTIPLICATION,
DIVISION
};
double performOperation(double a, double b, MathOperation op) {
switch (op) {
case ADDITION:
return a + b;
case SUBTRACTION:
return a - b;
case MULTIPLICATION:
return a * b;
case DIVISION:
return a / b;
default:
std::cout << "Invalid operation!" << std::endl;
return 0.0;
}
}
int main() {
double result = performOperation(5.0, 2.0, ADDITION);
std::cout << "Result: " << result << std::endl;
return 0;
}
Conclusion
Enums in C++ provide a convenient way to define a set of named values as constants. They help make code more readable and maintainable by giving meaningful names to the possible values. You can use enums in variable declarations, function parameters, and return types to represent a fixed set of options or states. Understanding how to use enums in C++ will enhance your ability to write clean and organized code.