C++ Enum

🎯 C++ enum – Name Your Numbers with Style

Ever got tired of writing 0, 1, 2 for different options? Use enum to give names to those numbers! It’s like giving roles to the cast of your program. 🎭

Enum (short for “enumeration”) lets you define your own set of named integer constants. It makes code easier to read, write, and remember.

🛠️ Syntax

enum EnumName {
    VALUE1,
    VALUE2,
    VALUE3
};

By default, the first value starts from 0 and increases by 1.

🔧 Example: Basic enum in C++

#include <iostream>
using namespace std;

enum Day {
    MONDAY,    // 0
    TUESDAY,   // 1
    WEDNESDAY  // 2
};

int main() {
    Day today = TUESDAY;

    if (today == TUESDAY) {
        cout << "It's Tuesday. Let's write some code!" << endl;
    }

    return 0;
}
  

Try It Now

🧮 Want Custom Values?

You can assign specific values to the enum constants if you don’t want them to start from 0.

#include <iostream>
using namespace std;

enum Status {
    SUCCESS = 200,
    NOT_FOUND = 404,
    SERVER_ERROR = 500
};

int main() {
    Status code = NOT_FOUND;

    cout << "Error code: " << code << endl;

    return 0;
}
  

Try It Now

📌 Quick Notes

  • Enum values are integers behind the scenes.
  • They make your code more readable and less error-prone.
  • You can use them in switch, if, and loops like regular numbers.

🧠 Simple Way to Remember

One thing, many names: Use enum when you want to name your numbers!