What an enum is
An enum, short for enumeration, is a type whose values come from a fixed list of names that you write yourself. Instead of remembering that 2 means “shipped,” you give the value a name and let the compiler handle the number behind it.
Enums suit values that can only be one of a small set of choices, such as directions, days of the week, or the states of a traffic light. This guide covers the syntax, the rules for numbering, and the scoped form added in C++11. It also covers C, where enums are close to C++ but not identical.
Basic enum syntax
This is a small, complete enum example in C++:
#include <iostream>
enum Color { RED, GREEN, BLUE };
int main() {
Color favorite = GREEN;
std::cout << favorite << "\n"; // prints 1
return 0;
}
The pieces work like this:
enum Colordeclares a new type calledColor.RED,GREEN, andBLUEare the enumerators, the named values of that type.- The closing
};needs its semicolon. Forgetting it is a common compile error. Color favorite = GREEN;creates a variable of the type and sets it to one enumerator.
How values are numbered
Enumerators are numbered from 0 unless you say otherwise, and each one is 1 more than the one before it. In the example, RED is 0, GREEN is 1, and BLUE is 2. That is why the program printed 1 for favorite.
Because an unscoped enum converts to a plain integer, you can also compare it with numbers, such as favorite == 1. That works, but it is usually clearer to compare with the name.
Setting your own values
You can assign a value to any enumerator. Names without a value keep counting from the name before them.
enum HttpStatus {
OK = 200,
NOT_FOUND = 404,
SERVER_ERROR = 500
};
enum Step {
FIRST = 10,
SECOND, // 11
THIRD // 12
};
Two names can share a value. C and C++ both allow this, but it can confuse readers, so use it only when you mean it.
Scoped enums with enum class
Since C++11, you can declare a scoped enum with enum class. Its names live inside the enum, so you write Direction::North instead of North.
#include <iostream>
enum class Direction { North, East, South, West };
int main() {
Direction heading = Direction::East;
if (heading == Direction::East) {
std::cout << "Heading east\n";
}
// std::cout << heading; // compile error: no implicit conversion to int
std::cout << static_cast<int>(heading) << "\n"; // prints 1
return 0;
}
Scoped enums help in two ways:
- Names don’t leak into the surrounding scope. Two scoped enums can each have a
Northwithout a clash. - They don’t convert to integers on their own. You use
static_cast<int>to get the number, so the conversion is visible in the code.
Plain enums are shorter to write and convert to int automatically, which is sometimes convenient. The trade-off is that an unscoped enum’s names go into the surrounding scope. Two unscoped enums declared in the same scope can’t both have a North.
Enums in C
Enums in C look much the same, with two differences that matter when you start. In C, you must write the enum keyword when you declare a variable. Also, enumerator names have type int, and C has no enum class.
#include <stdio.h>
enum Color { RED, GREEN, BLUE };
int main(void) {
enum Color favorite = GREEN;
printf("%d\n", favorite); // prints 1
return 0;
}
Many C programs use typedef so that the enum keyword isn’t needed each time:
typedef enum { RED, GREEN, BLUE } Color;
Color favorite = GREEN;
Using enums with switch
A switch is the usual tool for acting on each enum value. Write one case per enumerator. For the rules of the switch syntax itself, see switch case statement in c.
const char* directionName(Direction d) {
switch (d) {
case Direction::North: return "North";
case Direction::East: return "East";
case Direction::South: return "South";
case Direction::West: return "West";
}
return "Unknown"; // a value cast from an int that matches no name
}
Turn on warnings as well. With GCC or Clang, add -Wall. If a switch on an enum leaves out an enumerator and has no default, the compiler warns about it. When you add a new name later, that warning points you to each switch that needs updating.
Printing an enum’s name
C and C++ don’t turn an enum value into its name for you. Printing favorite shows a number. For an unscoped enum, a simple option is an array of names in the same order as the enumerators:
#include <iostream>
enum Color { RED, GREEN, BLUE };
int main() {
const char* names[] = {"RED", "GREEN", "BLUE"};
Color favorite = GREEN;
std::cout << names[favorite] << "\n"; // prints GREEN
return 0;
}
The array and the enum must stay in step, so update both when you add a value. For an enum class, you would need a static_cast<int> before indexing, and the switch function shown earlier is often clearer. You can also write your own << operator for the type, which is covered in operator overloading in c.
Choosing an underlying type
Every enum has an underlying integer type. For an enum class, that type is int unless you choose another. Since C++11, you can name it after a colon:
#include <cstdint>
enum class Level : std::uint8_t { Low = 1, Medium = 5, High = 10 };
A smaller type can save memory when you store many values, and it can match a binary file format. For most programs, the default int is fine. For the integer types themselves, see primitive data types in c.
Common mistakes
- Forgetting the semicolon after the closing brace.
- Assigning a plain number to an enum in C++.
Color c = 1;is an error, because integers don’t convert implicitly to enum types. In C, the same line compiles. - Leaving off the scope name. Writing
Northinstead ofDirection::Northfor anenum classwon’t compile. - Printing a name directly. Both C and C++ print the number.
- Trusting every value. A cast from an
intcan produce a number with no name. C and C++ don’t check for this, so handle unexpected values with adefaultcase or validate input first. - Relying on numbers you never set. If the numbers matter, for example when you save them to a file, assign them explicitly.
Summary
- An enum groups named integer constants under one type name.
- Plain enums are short to write and convert to
intautomatically. - An
enum classkeeps its names scoped and needs an explicit cast to get a number. - Use
switchwith-Wallto catch missing names. - Put enums in a header file with a header guard. Header guard in c explains how to write one.