Enumerations (enum) allow defining a set of named values. By default, each value takes a consecutive integer starting from 0.
Classic enum
enum Color { RED, GREEN, BLUE }; // RED=0, GREEN=1, BLUE=2
enum Day { MONDAY=1, TUESDAY=2, WEDNESDAY=3 }; // MONDAY=1, TUESDAY=2, WEDNESDAY=3
Color background = RED;Note
enumvalues automatically take consecutive integers (0, 1, 2, …), but you can assign them explicit values like inDay.
enum class (C++11)
enum class is the recommended form in modern C++: its values live in their own scope and are not implicitly converted to integers.
enum class Color { RED, GREEN, BLUE };
enum class NewColor { RED, GREEN }; // Names can be repeated without conflict
Color c = Color::RED; // The Color:: prefix must be usedWarning
Unlike the classic
enum,enum classis not implicitly converted toint. If you need the number, do an explicit cast:static_cast<int>(Color::GREEN).
Note
It is advisable to use
enum classto avoid name conflicts between multiple enums and to avoid accidental implicit conversions to integer.
Using the integer value
int value = static_cast<int>(Color::BLUE); // Explicitly converts to intNext: Functions