capypad
0 day streak
cpp / beginner
Snippet

Enumerations: Creating Named Constants

Enums allow you to create meaningful names for integral constants. Instead of using magic numbers like 1, 2, 3 throughout your code, you can define a Color enum with RED, GREEN, and BLUE. This makes your code more readable and easier to maintain.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
 
enum Color {
RED = 1,
GREEN = 2,
BLUE = 3
};
 
int main() {
Color favorite = GREEN;
if (favorite == GREEN) {
std::cout << "Green is awesome!" << std::endl;
}
return 0;
}
Breakdown
1
enum Color {
Starts defining an enumeration type named Color
2
RED = 1, GREEN = 2, BLUE = 3
Defines three named constants with explicit values
3
Color favorite = GREEN;
Creates a variable of type Color and assigns GREEN to it
4
if (favorite == GREEN)
Compares the enum variable using the named constant