Search

Meta

4.5 — Enumerated types

C++ allows programmers to create their own data types. Perhaps the simplest method for doing so is via an enumerated type. An enumerated type (also called an enumeration is a data type where every possible value is defined as a symbolic constant (called an enumerator). Enumerations are declared via the enum keyword. Let’s look at an example:

Declaring an enumeration 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 enums

Enum identifiers are often named starting with a capital letter, and the enumerators are often named using all caps. 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 be non-unique. 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. Generally assigning the same value to two enumerators in the same enumeration should be avoided.

Best practice: Don’t assign specific values to your enumerators.
Rule: 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:

5

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:

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 cannot forward declare enum types. However, there is an easy workaround. 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, functions often 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 each item needed to be categorized as a weapon, armor, consumable, or carryable. 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

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

2) Declare a variable of the enumerated type you defined in question 1 and assign it the troll type.

3) True or false. Enumerators can be:
3a) assigned integer values
3b) not assigned a value
3c) explicitly assigned floating point values
3d) negative
3e) non-unique
3f) assigned the value of prior enumerators (eg. COLOR_MAGENTA = COLOR_RED)

Quiz answers

1) Show Solution

2) Show Solution

3) Show Solution

4.5a -- Enum classes
Index
4.4b -- An introduction to std::string

34 comments to 4.5 — Enumerated types

  • 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.

  • 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?

    Thanks

    • 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.

  • 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:

  • 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).

  • 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).

  • Shai

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

  • 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

    EDIT:
    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

    Strange.

    • 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.

  • SWEngineer

    Simple well explained tutorial. Thanks.

  • 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?

  • 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

  • KanedaSyndrome

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

    My contribution:

    prototype:

    enum monsters
    {
    ORC,
    GOBLIN,
    TROLL,
    OGRE,
    SKELETON,
    };

    declaraction and assignment

    monsters newMonster = TROLL;

    test:

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

    ~KanedaSyndrome

  • 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’|

    #include
    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.

  • dice3000

    Awesome tutorial. I actually learned something really useful

  • JesseZhuang

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

  • 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.

  • 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
    {
    MONSTER_ORC,
    MONSTER_GOBLIN,
    MONSTER_TROLL,
    MONSTER_OGRE,
    MONSTER_SKELETON, <--
    };

    • 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.

  • 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?

  • 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.

  • 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.

    Jana

    • 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.

Leave a Comment

  

  

  

6 + 4 =

Put C++ code inside [code][/code] tags to use the syntax highlighter