C++ Enums

Creating named constants for better code readability

🏷️ What are C++ Enums?

C++ enums (enumerations) are user-defined data types that consist of named constants, making code more readable and maintainable by replacing magic numbers with meaningful names.


// Simple enum example
enum Color {
    RED, GREEN, BLUE
};
                                    

Enum Concepts

📝

Basic Enum

Simple enumeration with default values

enum Day {
    MONDAY, TUESDAY, WEDNESDAY
};
🔢

Custom Values

Assign specific values to enum constants

enum Grade {
    A = 90, B = 80, C = 70
};
🛡️

Scoped Enum

Type-safe enums with scope (C++11)

enum class Status {
    ACTIVE, INACTIVE, PENDING
};
🎯

Usage

Use enum values in your code

Color myColor = RED;
if (myColor == RED) {
    // Do something
}

🔹 Basic Enum Example

An enumeration (enum) in C++ is a user-defined data type that consists of named integer constants, improving code readability and reducing errors. To define a basic enum, use the enum keyword followed by a name and a list of identifiers inside braces, like enum Color { RED, GREEN, BLUE };. Each identifier is automatically assigned an integer value starting from 0. Enums are ideal for representing a fixed set of related values, such as days of the week, menu options, or system states, making your code more self-documenting and less prone to magic number usage.

#include <iostream>
using namespace std;

// Define an enum
enum TrafficLight {
    RED,     // 0 by default
    YELLOW,  // 1
    GREEN    // 2
};

int main() {
    TrafficLight light = RED;
    
    switch(light) {
        case RED:
            cout << "Stop! Light is RED" << endl;
            break;
        case YELLOW:
            cout << "Caution! Light is YELLOW" << endl;
            break;
        case GREEN:
            cout << "Go! Light is GREEN" << endl;
            break;
    }
    
    cout << "RED value: " << RED << endl;
    cout << "YELLOW value: " << YELLOW << endl;
    cout << "GREEN value: " << GREEN << endl;
    
    return 0;
}

Output:

Stop! Light is RED
RED value: 0
YELLOW value: 1
GREEN value: 2

🔹 Enum with Custom Values

C++ allows you to assign specific integer values to enum constants, providing precise control over their underlying representation. Instead of relying on automatic numbering, you can explicitly set values, such as enum HttpStatus { OK = 200, NOT_FOUND = 404, SERVER_ERROR = 500 };. This is especially useful when the values correspond to external codes, hardware registers, or protocol-specific numbers. Custom values can be assigned in any order, and multiple constants can share the same value, enabling flexible and meaningful mappings for applications like error handling, state machines, or configuration settings.

#include <iostream>
using namespace std;

enum Size {
    SMALL = 10,
    MEDIUM = 20,
    LARGE = 30,
    EXTRA_LARGE = 40
};

enum Priority {
    LOW = 1,
    NORMAL,     // 2 (automatically incremented)
    HIGH,       // 3
    CRITICAL = 10
};

int main() {
    Size shirtSize = MEDIUM;
    Priority taskPriority = HIGH;
    
    cout << "Shirt size value: " << shirtSize << endl;
    cout << "Task priority: " << taskPriority << endl;
    
    if (taskPriority >= HIGH) {
        cout << "This is a high priority task!" << endl;
    }
    
    return 0;
}

Output:

Shirt size value: 20
Task priority: 3
This is a high priority task!

🔹 Scoped Enums (enum class)

Introduced in C++11, scoped enums (enum classes) offer enhanced type safety by preventing implicit conversions and keeping constants within a distinct scope. Declared with enum class, they require explicit scoping to access values, like Color::RED, avoiding naming conflicts and accidental comparisons with integers. For example, enum class Status { SUCCESS, FAILURE }; ensures Status::SUCCESS cannot be mistakenly compared to a plain integer. This reduces bugs, improves code clarity, and is recommended for modern C++ development, especially in large projects where name collisions and type errors are common concerns.

#include <iostream>
using namespace std;

enum class Animal {
    DOG,
    CAT,
    BIRD
};

enum class Vehicle {
    CAR,
    BIKE,
    TRUCK
};

int main() {
    Animal pet = Animal::DOG;
    Vehicle transport = Vehicle::CAR;
    
    // Must use scope resolution operator
    if (pet == Animal::DOG) {
        cout << "Pet is a dog" << endl;
    }
    
    if (transport == Vehicle::CAR) {
        cout << "Transport is a car" << endl;
    }
    
    // This would cause a compilation error:
    // if (pet == transport) // Different enum types!
    
    // To get underlying value, cast is needed
    cout << "Dog value: " << static_cast<int>(Animal::DOG) << endl;
    
    return 0;
}

Output:

Pet is a dog
Transport is a car
Dog value: 0

🔹 Practical Enum Example

Enums are powerful for representing distinct states or modes in applications, such as game states, UI screens, or process statuses. For instance, a game might use enum class GameState { MENU, PLAYING, PAUSED, GAME_OVER }; to manage transitions between different screens. By switching based on the current enum value, the code becomes highly organized and maintainable. This approach eliminates ambiguous strings or numbers, centralizes state definitions, and simplifies debugging, making it invaluable for game development, user interface workflows, and finite state machines in embedded or desktop software.

#include <iostream>
#include <string>
using namespace std;

enum class GameState {
    MENU,
    PLAYING,
    PAUSED,
    GAME_OVER
};

string getStateDescription(GameState state) {
    switch(state) {
        case GameState::MENU:
            return "Main Menu";
        case GameState::PLAYING:
            return "Game in Progress";
        case GameState::PAUSED:
            return "Game Paused";
        case GameState::GAME_OVER:
            return "Game Over";
        default:
            return "Unknown State";
    }
}

int main() {
    GameState currentState = GameState::MENU;
    
    cout << "Current state: " << getStateDescription(currentState) << endl;
    
    // Change state
    currentState = GameState::PLAYING;
    cout << "New state: " << getStateDescription(currentState) << endl;
    
    return 0;
}

Output:

Current state: Main Menu
New state: Game in Progress

🧠 Test Your Knowledge

What is the default value of the first enum constant?