capypad
0 day streak
cpp / beginner
Snippet

Enumerations: Named Integer Constants

An enumeration defines a set of named integer constants. By default, values start at 0 and increment. You can explicitly assign values as shown. Enums make code more readable by replacing magic numbers with descriptive names like RED, GREEN, and BLUE.

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 myColor = GREEN;
if (myColor == 2) {
std::cout << "It's green!" << std::endl;
}
return 0;
}
Breakdown
1
enum Color { RED = 1, GREEN = 2, BLUE = 3 };
Defines a new type Color with three named constants, starting at 1 instead of 0
2
Color myColor = GREEN;
Declares a variable of type Color and assigns the value GREEN (2)