8.2 — Enumerated types

C++ contains quite a few built in data types. But these types aren’t always sufficient for the kinds of things we want to do. So C++ contains capabilities that allow programmers to create their own data types. These data types are called user-defined data types.

Perhaps the simplest user-defined data type is the enumerated type. An enumerated type (also called an enumeration or enum) is a data type where every possible value is defined as a symbolic constant (called an enumerator). Enumerations are defined via the enum keyword. Let’s look at an example:

Defining an enumeration (or any user-defined data type) does not allocate any memory. When a variable of the enumerated type is defined (such as variable paint in the example above), memory is allocated for that variable at that time.

Note that each enumerator is separated by a comma, and the entire enumeration is ended with a semicolon.

Naming enumerations and enumerators

Providing a name for an enumeration is optional, but common. Enums without a name are sometimes called anonymous enums. Enumeration names are often named starting with a capital letter.

Enumerators must be given names, and typically use the same name style as constant variables. Sometimes enumerators are named in ALL_CAPS, but doing so is discouraged, because it risks collisions with preprocessor macro names.

Enumerator scope

Because enumerators are placed into the same namespace as the enumeration, an enumerator name can’t be used in multiple enumerations within the same namespace:

Consequently, it’s common to prefix enumerators with a standard prefix like animal_ or color_, both to prevent naming conflicts and for code documentation purposes.

Enumerator values

Each enumerator is automatically assigned an integer value based on its position in the enumeration list. By default, the first enumerator is assigned the integer value 0, and each subsequent enumerator has a value one greater than the previous enumerator:

The cout statement above prints the value 4.

It is possible to explicitly define the value of enumerator. These integer values can be positive or negative and can share the same value as other enumerators. Any non-defined enumerators are given a value one greater than the previous enumerator.

Note in this case, animal_horse and animal_giraffe have been given the same value. When this happens, the enumerations become non-distinct -- essentially, animal_horse and animal_giraffe are interchangeable. Although C++ allows it, assigning the same value to two enumerators in the same enumeration should generally be avoided.

Best practice

Don’t assign specific values to your enumerators.


Don’t assign the same value to two enumerators in the same enumeration unless there’s a very good reason.

Enum type evaluation and input/output

Because enumerated values evaluate to integers, they can be assigned to integer variables. This means they can also be output (as integers), since std::cout knows how to output integers.

This produces the result:


The compiler will not implicitly convert an integer to an enumerated value. The following will produce a compiler error:

However, you can force it to do so via a static_cast:

The compiler also will not let you input an enum using std::cin:

One workaround is to read in an integer, and use a static_cast to force the compiler to put an integer value into an enumerated type:

Each enumerated type is considered a distinct type. Consequently, trying to assign enumerators from one enum type to another enum type will cause a compile error:

If you want to use a different integer type for enumerators, for example to save bandwidth when networking an enumerator, you can specify it at the enum declaration.

Since enumerators aren’t usually used for arithmetic or comparisons, it’s safe to use an unsigned integer. We also need to specify the enum base when we want to forward declare an enum.

As with constant variables, enumerated types show up in the debugger, making them more useful than #defined values in this regard.

Printing enumerators

As you saw above, trying to print an enumerated value using std::cout results in the integer value of the enumerator being printed. So how can you print the enumerator itself as text? One way to do so is to write a function and use an if statement:

Once you’ve learned to use switch statements, you’ll probably want to use those instead of a bunch of if/else statements, as it’s a little more readable.

Enum allocation and forward declaration

Enum types are considered part of the integer family of types, and it’s up to the compiler to determine how much memory to allocate for an enum variable. The C++ standard says the enum size needs to be large enough to represent all of the enumerator values. Most often, it will make enum variables the same size as a standard int.

Because the compiler needs to know how much memory to allocate for an enumeration, you can only forward declare them when you also specify a fixed base. Because defining an enumeration does not allocate any memory, if an enumeration is needed in multiple files, it is fine to define the enumeration in a header, and #include that header wherever needed.

What are enumerators useful for?

Enumerated types are incredibly useful for code documentation and readability purposes when you need to represent a specific, predefined set of states.

For example, old functions sometimes return integers to the caller to represent error codes when something went wrong inside the function. Typically, small negative numbers are used to represent different possible error codes. For example:

However, using magic numbers like this isn’t very descriptive. An alternative method would be through use of an enumerated type:

This is much easier to read and understand than using magic number return values. Furthermore, the caller can test the function’s return value against the appropriate enumerator, which is easier to understand than testing the return result for a specific integer value.

Enumerated types are best used when defining a set of related identifiers. For example, let’s say you were writing a game where the player can carry one item, but that item can be several different types. You could do this:

Or alternatively, if you were writing a function to sort a bunch of values:

Many languages use Enumerations to define booleans. A boolean is essentially just an enumeration with 2 enumerators: false and true! However, in C++, true and false are defined as keywords instead of enumerators.

Quiz time

Question #1

Define an enumerated type to choose between the following monster races: orcs, goblins, trolls, ogres, and skeletons.

Show Solution

Question #2

Define a variable of the enumerated type you defined in question 1 and initialize it with the troll enumerator.

Show Solution

Question #3

True or false. Enumerators can be:
3a) given an integer value
3b) not assigned a value
3c) given a floating point value
3d) negative
3e) non-unique
3f) initialized with the value of prior enumerators (e.g. color_magenta = color_red)

Show Solution

8.3 -- Enum classes
8.1 -- Using a language reference

322 comments to 8.2 — Enumerated types

  • Jim

    Making your own data type using enum Color and auto. assigning COLOR_BLACK a value 0 all seems pretty simple for just 7 color.

    What's going to be hard is defining all the colors to make up a pallet (2^8)256 or more and how and what you need to do to use them.

    So can I assume some of this has already been done for us in C++? Or maybe we can find this in some library out there?

    • Alex

      Enums are useful when you have well defined set of things that have discrete names.

      For something like a palette of 256 colors, I probably wouldn't use an enum. Creating names for all 256 colors and setting up huge switches to handle them doesn't seem efficient or readable. At that point, you're probably better of just passing an RGB color value.

  • begginner

    using namespace std;
    enum Monster{
    function(Monster monster){
            cout<<"you choose a RAT!";
            cout<<"you choose a LORD!";
            cout<<"you choose a DRAGON!";
                cout<<"you choose a BULL!";
                cout<<"you choose a DOG!";
    why i am getting extra valur after my enum type.

  • Night Owl

    Hello Alex,

    On the quiz part of this section, what do you mean by " enumerators can be non-unique"?

    I know many people have said this, but thanks for all you hard work on the lessons and this website.

    • Alex

      I updated the wording to be more clear:

      "These integer values can be positive or negative and can share the same value as other enumerators"

      Basically, two different enumerators can resolve to the same value.

  • Vishnu

    I think there are ; missing from the game(sword,torch etc) example given above after the return statements defined under "string getItemName(.....)"  .

    Please correct me if I am wrong. :)

  • techsavvy....aye

    In the first answer of quiz I think the last enumeration shouldn't have a ','.

  • techsavvy....aye

    Oh!! got it I was putting a small 'c' for 'color' instead of 'Color'.
    got it, thanks!

  • techsavvy....aye

    How can I output in the above program I tried many things but couldn't. It must be some small mistake could you tell me how to do it.

    • Alex

      I don't understand what problem you are having. Did you try this?

  • techsavvy....aye

    How to use switch statements for the program

    • Alex

      Switch statements for enums are covered in lesson 5.3 -- Switch statements.

    • saeid

  • Anuj

    In the line number
    11.std::string getItemName(ItemType itemType)..."getItemName is a keyword or anything can be written with get??

  • Todd


    "An enumerated type (also called an enumeration is a data type..." (insert an end parentheses after "enumeration")

  • Eric

    I'm reading your tutorial as a precursor to a C++ video game development tutorial, so obviously this example intrigued me. But I don't understand how it is useful.  So you've a got string ("torch"), you have an enum called itemType with value (ITEMTYPE_CARRYABLE), but how are those in anyway related?  How could you use those in context?  I mean, if you were trying to "use" the torch and decide what to do with it, how would your function know that "torch" was a "ITEMTYPE_CARRYABLE"?  I'm really frustrated because I feel like this example went right over my head, but it seems extremely useful.  Would really love some clarification!

    • Alex

      The short answer is that the example I provided wasn't very good. I've updated the example to one that I think is more straightforward. Check it out and let me know if that answers your question.

      It is common to use enums to define "categories" of things (like I did in the original example you quoted). These can be used in many different ways. For example, if you had an array of all the items in your game, it might be useful to assign a type to each item so that you'd know how to handle them (e.g. weapons get held, armor gets worn, consumables get used).

      Alternatively, each of your items could have a type (as defined in the example you quoted) and a subtype (that specifies whether the weapon is a sword or a dagger or a bow, or the carryable is a torch or a shield), and use them in pairs.

  • Jana

    Hi Alex,

    In your last comment, line 12 of the code: Color color = BLUE; What do 'Color' and 'color' refer to?
    I expect that 'Color' is the enum identifier, but not sure about the other one.

    Also, why do you sometimes use eColor (e.g. in Enum type evaluation and input/output)?

    Thanks a lot.


    • Alex

      This declares a variable named color of type Color (which is an enumeration defined previously), and then sets the value of color to BLUE.

      When this lesson was first written, I used the prefix "e" on all enumerator variables. Since then, I've moved away from that naming convention, but I missed one instance. It's updated now.

  • jianping

    in the example:

    what if there are two enumerators with assigned value 5?

    • Alex

      It still works. Enumerators aren't guaranteed to be distinct, so two enumerators with the same value are essentially interchangeable.

      Although it doesn't make any sense:

      This prints "Color is equal to GREEN" because we assigned the same value to the enumerators BLUE and GREEN.

      In short, the takeaway is that generally you shouldn't assign the same value to two enumerators in the same enumeration.

      • ColorMan

        What if:

        It works for me! Althought Color enumeration has only 8 Colors!
        Great Tuts!
        P.S: You should add a union section after this one. ;)

        • Alex

          Yup, you can cast an integer to an enumeration value that doesn't have an associated enumerator.

          I'll think about adding a lesson on unions. They're not used very often, but they can be interesting in some cases.

        • Yousuf

          GCC Compiler 10.2.0:

          It worked for me without "-Werror=conversion" this compiler flag but compiler immediately showed an error of out of range with this flag "-Werror=conversion".

  • Jeremy

    I'm having a heck of a time trying to figure out how to forward declare enumerated classes/structs (same thing, I know). I know you haven't touched on scoped and unscoped enums here yet, but you probably will in the future. I think they're cool and all, but I can't figure out how to make a forward declaration work for them. It seems easier to just stuff the whole definition in a header file and include it to avoid the headache, but surely forward declarations for enums (and structs for that matter) exist for a reason?

  • Joseph

    Should the last enumerator variable have a comma after it?
    Wouldn't the compiler expect another variable to follow and give an error? Mine doesn't so I don't know if this is okay or not.

    enum MonsterType

    • Alex

      This is a surprisingly complicated answer.

      C++ didn't allow the last enumerator to have a comma until C++11, where they started allowing it.
      C didn't allow the last enumerator to have a comma until C99.

      So it really depends on what set of standards your compiler adheres to. Any C++11 compatible compiler should allow it. Any pre-C++11 compiler may or may not allow it for C99 compatibility purposes. It sounds like yours does allow it.

  • Subhan

    Can't I set enumerated values to be greater than int values? Example

    • Alex

      The C++ standard says: "It is implementation-defined which integral type is used as the underlying type for an enumeration except that the underlying type shall not be larger than int unless the value of an enumerator cannot fit in an int or unsigned int".

      So in theory, if you have an enumerated value that is larger than an int, the compiler should pick a larger integral type. Visual Studio 2010 errors on your example because it doesn't have any integral types larger than int. Compilers compliant with C++11 should allow this though, as they could pick a long long integral type.

  • JesseZhuang

    Is non-unique enumerators useful in any case in practice?

  • dice3000

    Awesome tutorial. I actually learned something really useful

  • Jannat

    Hi. I found these enumerated types really interesting. So I tried to make this program.
    I keep on getting the following error.

    error: no match for 'operator>>' in 'std::cin >> eColour'|

    using namespace std;
    int main ()
    { //program to input a colour and output the lucky number. lol
    enum colour
    red = 1,
    blue = 2,
    green = 3,
    colour eColour = red;
    cout<<"Choose a colour "<>eColour ;
    cout <<" Your lucky number is "<<eColour<<endl;
    return 0;

    What's wrong with cin ? can these enumerated data types not be input?

    • Alex

      No, you can't use cin to input enumerated types. If you want to do this, have the user input an integer and then use a static_cast to convert it to your enumType.

  • KanedaSyndrome

    This was an area that I haven't worked with before, so it was fun to get into.

    My contribution:


    enum monsters

    declaraction and assignment

    monsters newMonster = TROLL;


    cout << endl << newMonster; //outputs the value 2


  • kalvin

    Enumerations are a little confusing for me. I would better understand them if i had a practical use for them.. I know that no arithmetic operations are allowed on enum, and that since enums are an ordered set of values, you can use relational operators, and loops. this being said I guess I can see how using enum to make your program more readable might be benificial. But to really incorperate enums into your program you will have to input and output enums indirectly as you can not directly output or input enumeration data types.. So for now , i think you have to choose whether to make your program more readable with more work using enumerations, or not and save the extra programming.. Idk maybe as i learn and play with this more i will find its practicality

  • newUser

    If I had not read the comments I would have never noticed enum uses commas! May I suggest having it written in the tutorial too so it draws more attention to it?

  • SWEngineer

    Simple well explained tutorial. Thanks.

  • John

    I hope that is all in code !

    When I run this, I get the exception in the PrintBodyPartStatus(), which prints 0 0.
    And the check above the exception, is expecting a 0, 0.
    What am I missing? Am I doing this wrong? It seems like a viable way to use Enums, as I've been using consts for EVERYTHING until I had a look at some open source game Enums.

    I'm currently working on this, so don't think I'm commenting to expect you to do it for me (which would be nice, I admit)
    But I really didnt't see the point in typing out

    where in a few less line I coult just type in

    Thanks in advance

    changing the check from && to || make it work. I've always wondered why OR checks work properly and AND checks don't. (Maybe I've been doing those all wrong too, but I've always had the problem, even on simple checks.

    even compound if's don't work very often


    • Luiwtf

      should be:

      note the 2 ='s, instead of one :)

      the reason it works with || is because the second half comes up true as you have the == correct, as it is the first part is irrelevant.

      edit - meh, just noticed it's a month old :D, i suck at remembering dates :p.

  • Shai

    Great work, Alex.
    Your site is better than any C++ book I know of.

  • Sim

    Is there any other situation, in which enumerators are needed typically? Cause as of now I don't see any difference between doing this:

    and this:

    Obviously these are constants, thus they cannot be changed during runtime. However, if this is the only typical way of using enumerator types, then I don't see why you wouldn't just pre-define them using the preprocessor.

    • Alex

      As I noted above, Enums are always a better choice than #define when you have a set of options to pick from because the syntax checking will exclude you from picking something not part of the enum set. Plus they’re more readable, and debuggers can resolve their values (whereas debuggers generally can not resolve the values of #defines).

  • Kinten

    I dont see the reason for usin enums instead of macros, I mean, if you use the enum it is necesary to initiate at least one instance of it, while the macros (#define) replace everyting right away without the memory cost.
    Isn't this a better solution?

    • Enums and #defines have the same memory requirements. Enum definitions take up no additional memory space because they are just definitions. A good compiler should replace any enum with its integer equivalent at compile time, just like #defines are replaced by the preprocessor.

      Enums are always a better choice than #define when you have a set of options to pick from because the syntax checking will exclude you from picking something not part of the enum set. Plus they're more readable, and debuggers can resolve their values (whereas debuggers generally can not resolve the values of #defines).

  • Rousseaux

    i will have to reread this lesson later. But i'm with Ben as far as seeing more use in the name of the enum type being printed in the stead of the actual integer. i tried to find a way to cout the name by feeding the integer value but that skill is beyond my scope so far. Once again you've fueled new 'what if's' Alex. Well done.

    • If I need the names of a set of enums for something, I'll usually write a function that takes the enum name to be printed and return a string version of the enum. Something like this:

  • Ben

    Not sure I understand its interest. If you're trying to get a more understandable error message for example, I don't see much difference as it will still print an integer and not "ERROR_OPENING_FILE". Same idea with a list of names, etc...
    Is there a way to print the name of the enum and not its integer value?


    • Unfortunately, there's no easy way to print the name of the enum. The main benefits of using enums are:
      1) Code readability is enhanced, since enums are descriptions and numbers could mean anything
      2) If you ever want to change an enum's corresponding integer value, you only have to do so in one place, whereas if you use integers everywhere, you might have to change multiple values.

      Enums are often used in conjunction with functions, either as parameters or return values to denote a particular mode or state.

  • tom mason

    When are the enumerators created? Can they be used independently of the enum-type variable? It appears that they are declared as -static const int-

    • Enums are handled at compile time, and they are generally treated as a const int. There is no such thing as a static type, so the static keyword is not applicable. The scope of enum type declarations is the same as normal variables: Enums declared outside of a class or function are treated as global, those inside a block are scoped to that block, and those in a class are considered part of that class.

      For example:

      Enum values can be used independently of the enum-type variable, as they are essentially treated as integers. For example, the following is valid:

      Note that in the specification for the next version of C++ (C++0x), there will be a new type of enum (called a strongly typed enum) that will be treated as a unique type. These strongly typed enums will not be implicitly convertable to integers.

      • Sasan

        Can we define all of our Enums in a separate file (.cpp) and forward declaration them in a Header file and then include that? I tried to do that but compiler gave me error on this (in header file):

        enum Color;

        • Alex

          No, you can't forward declare enums.

          However, there's no need. Because defining an enum doesn't use any memory, it's fine to define your enum types in a header and #include that header wherever you need access to the enum type.

Leave a Comment

Put all code inside code tags: [code]your code here[/code]