cpp / beginner
Snippet
Enumerated Types: Creating Named Constants
An enum creates a custom data type with named integer constants. By default, the first value is 0, but you can assign specific values. Enums make code more readable by replacing magic numbers with descriptive names.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>using namespace std;enum Difficulty { EASY, MEDIUM, HARD };int main() {Difficulty level = MEDIUM;if (level == EASY) {cout << "Easy mode" << endl;}return 0;}
Breakdown
1
enum Difficulty { EASY, MEDIUM, HARD };
Creates a new type where EASY=0, MEDIUM=1, HARD=2
2
Difficulty level = MEDIUM;
Declares a variable of the enum type