cpp / beginner
Snippet
Enumerations Basics
Enumerations allow you to define named constant values, making code more readable and maintainable. Instead of using arbitrary numbers throughout your code, you can use meaningful names like RED or GREEN. Enums are particularly useful when a variable can only take one of a limited set of values, such as days of the week or color choices.
snippet.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 = RED;if (favorite == RED) {std::cout << "Red is selected" << std::endl;}return 0;}
Breakdown
1
enum Color { RED = 1, ...}
Defines a new type with named constant values
2
Color favorite = RED;
Creates variable of enum type assigned to RED
3
favorite == RED
Can compare enum values directly using their names