Enums

What Is an Enum? A Simple Example

Enum is short for enumeration. See a simple enum example in C++ that names traffic light states, and learn why the names make code easier to read.

On this page
  1. What an enum is
  2. A simple example
  3. Why names beat numbers
  4. Things to keep in mind

What an enum is

Enum is short for enumeration. An enum is a list of named values. Each name stands for a number, and the compiler assigns the numbers for you unless you choose them yourself.

A simple example

Here is a short C++ program with three traffic light states:

#include <iostream>

enum TrafficLight { RED_LIGHT, YELLOW_LIGHT, GREEN_LIGHT };

int main() {
    TrafficLight light = YELLOW_LIGHT;

    if (light == YELLOW_LIGHT) {
        std::cout << "Slow down\n";
    }
    return 0;
}

The program prints Slow down. Here is what each part does:

  • enum TrafficLight defines a type with three names.
  • RED_LIGHT is 0, YELLOW_LIGHT is 1, and GREEN_LIGHT is 2, because numbering starts at 0.
  • light is a variable that holds one of those names.
  • The if compares light with a name, so the code says what it checks.

Why names beat numbers

Compare these two lines:

if (light == 1) { /* ... */ }
if (light == YELLOW_LIGHT) { /* ... */ }

With an unscoped enum, both lines compile. The second one says what it checks, though. Anyone reading the code knows which state is being tested without looking up a table.

Things to keep in mind

  • Names in the same scope must be unique.
  • The numbers follow the order you wrote them in. If the exact numbers matter, set them yourself.
  • A name isn’t text. Printing YELLOW_LIGHT as a word takes extra code, such as an array of names.
  • To act on each state, a switch is the usual tool. The rules are in switch case statement in c.

The complete guide to enums

Enums in C++ With Examples
Read the guide

Keep exploring

Guides from other topics

All topics →

Tuples in C++ With std::tuple

Learn how std::tuple groups a fixed number of values of mixed types in C++. Covers creating tuples, reading them with std::get and structured bindings.

Tuples 4 min read