Why do you use typedef when declaring an enum in C++?

Tim Merrifield picture Tim Merrifield · Dec 21, 2008 · Viewed 192.4k times · Source

I haven't written any C++ in years and now I'm trying to get back into it. I then ran across this and thought about giving up:

typedef enum TokenType
{
    blah1   = 0x00000000,
    blah2   = 0X01000000,
    blah3   = 0X02000000
} TokenType;

What is this? Why is the typedef keyword used here? Why does the name TokenType appear twice in this declaration? How are the semantics different from this:

enum TokenType
{
    blah1 = 0x00000000,
    blah2=0x01000000,
    blah3=0x02000000
};

Answer

Ryan Fox picture Ryan Fox · Dec 21, 2008

In C, declaring your enum the first way allows you to use it like so:

TokenType my_type;

If you use the second style, you'll be forced to declare your variable like this:

enum TokenType my_type;

As mentioned by others, this doesn't make a difference in C++. My guess is that either the person who wrote this is a C programmer at heart, or you're compiling C code as C++. Either way, it won't affect the behaviour of your code.