views:

291

answers:

4

The standard way of declaring an enum in C++ seems to be:

enum <identifier> { <list_of_elements> };

However, I have already seen some declarations like:

typedef enum { <list_of_elements> } <identifier>;

What is the difference between them, if it exists? Which one is correct?

+14  A: 

C compatability.

In C, union, struct and enum types have to be used with the appropriate keyword before them:

enum x { ... };

enum x var;

In C++, this is not necessary:

enum x { ... };

x var;

So in C, lazy programmers often use typedef to avoid repeating themselves:

typedef enum x { ... } x;

x var;
Chris Lutz
Just want to note that I'm not using "lazy" pejoratively here.
Chris Lutz
indeed, it is one of that qualities that make a good programmer :)
aib
Impatience and hubris being the others.
Steve Jessop
ROFL @Steve You nailed it! :D
Soham
@Soham: not me, Larry Wall :-)
Steve Jessop
So be it then, so be it.Dont you think the hubris bit was a sarcasm.
Soham
+3  A: 

I believe the difference is that in standard C if you use

enum <identifier> { list }

You would have to call it using

enum <identifier> <var>;

Where as with the typedef around it you could call it using just

<identifier> <var>;

However, I don't think it would matter in C++

Shaded
+3  A: 

Similar to what @Chris Lutz said:

In old-C syntax, if you simply declared:

enum myEType {   ... };

Then you needed to declare variables as:

enum myEType myVariable;

However, if you use typedef:

typedef enum {   ... } myEType;

Then you could skip the enum-keyword when using the type:

myEType myVariable;

C++ and related languages have done away with this restriction, but its still common to see code like this either in a pure C environment, or when written by a C programmer.

abelenky
A: 

Remember that if you where doing this is C (not C++), You wouldn't be writing 100% ansi compilant C because the ansi doesn't state the use of typedef in this(writing the typedef on the same line).

Silverrocker
This is not the way I indent my code. It's just an example.
freitass