Labs ICT
Pro Login

Enums

An enum (enumeration) lets you define a set of named constants. Instead of using magic numbers scattered through your code, you give meaningful names to values. This makes your code more readable and less error-prone.

Defining an Enum

You define an enum with the enum keyword. By default, the first enumerator gets the value 0, the next gets 1, and so on:

#include <iostream>

enum Color { RED, GREEN, BLUE };

int main() {
  Color c = GREEN;

  if (c == GREEN) {
    std::cout << "The color is green\n";
  }

  std::cout << "RED = " << RED << "\n";
  std::cout << "GREEN = " << GREEN << "\n";
  std::cout << "BLUE = " << BLUE << "\n";
  return 0;
}

RED is 0, GREEN is 1, BLUE is 2. The variable c is of type Color and can only hold one of the defined enumerators.

Specifying Values

You can assign specific integer values to enumerators. This is useful when you are mapping to specific codes or bit flags:

#include <iostream>

enum StatusCode {
  OK = 200,
  NOT_FOUND = 404,
  SERVER_ERROR = 500
};

int main() {
  StatusCode code = NOT_FOUND;

  std::cout << "Status code: " << code << "\n";

  if (code == NOT_FOUND) {
    std::cout << "Resource not found\n";
  }
  return 0;
}

You can also let one value follow another by just specifying the first:

enum Weekday { MON = 1, TUE, WED, THU, FRI, SAT, SUN };
// TUE = 2, WED = 3, ... SUN = 7

Switch with Enum

Enums pair beautifully with switch statements. The compiler can even warn you if you miss a case:

#include <iostream>

enum Level { EASY, MEDIUM, HARD };

int main() {
  Level L = MEDIUM;

  switch (L) {
    case EASY:
      std::cout << "Beginner mode\n";
      break;
    case MEDIUM:
      std::cout << "Intermediate mode\n";
      break;
    case HARD:
      std::cout << "Expert mode\n";
      break;
  }
  return 0;
}

Using an enum instead of raw integers means you never accidentally type a wrong number, and your intent is clear to anyone reading the code.

Enum Class (C++11)

C++11 introduced enum class — a strongly-typed enum. It does not implicitly convert to integers and its values are scoped to the enum name:

#include <iostream>

enum class Direction { NORTH, SOUTH, EAST, WEST };

int main() {
  Direction d = Direction::NORTH;

  if (d == Direction::NORTH) {
    std::cout << "Heading north\n";
  }

  int value = static_cast<int>(Direction::SOUTH);
  std::cout << "SOUTH as int: " << value << "\n";
  return 0;
}

Use enum class in modern C++ — it avoids name conflicts and prevents accidental comparisons with integers.