capypad
0 day streak
cpp / beginner
Snippet

Enumerations: Named Integer Constants

An enumeration defines a set of named integer constants. Traditional enums (like Color) are in the global scope, while enum class (like Priority) provides stronger type safety and requires the scope operator :: to access values. Enums make code more readable by replacing magic numbers with meaningful names.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
 
enum Color {
RED = 1,
GREEN = 2,
BLUE = 3
};
 
enum class Priority {
LOW = 1,
MEDIUM = 2,
HIGH = 3
};
 
int main() {
Color favorite = GREEN;
 
if (favorite == RED) {
std::cout << "Red is favorite" << std::endl;
} else if (favorite == GREEN) {
std::cout << "Green is favorite" << std::endl;
}
 
Priority p = Priority::HIGH;
std::cout << "Priority value: " << static_cast<int>(p) << std::endl;
 
return 0;
}
Breakdown
1
enum Color { RED = 1, GREEN = 2, BLUE = 3 };
Traditional enum with assigned integer values
2
enum class Priority { LOW, MEDIUM, HIGH };
Strongly-typed enum class requiring scope operator
3
static_cast<int>(p)
Converts enum class value to integer for output