Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between declaring an enum with and without 'typedef'?

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?

like image 615
freitass Avatar asked Apr 28 '10 21:04

freitass


People also ask

What is the use of typedef and enum in C?

Using the typedef and enum keywords we can define a type that can have either one value or another. It's one of the most important uses of the typedef keyword. This is the syntax of an enumerated type: typedef enum { //...

What is the difference between typedef and macro?

We can have symbolic names to datatypes using typedef but not to numbers etc. Whereas with a macro, we can represent 1 as ONE, 3.14 as PI and many more. We can have a type name and a variable name as same while using typedef. Compiler differentiates both.

What is the difference between enum and struct?

Enum is to define a collection of options available. A struct can contain both data variables and methods. Enum can only contain data types. A struct supports a private but not protected access specifier.

What is the difference between enum and #define in C?

One of the differences between the two is that #define is a pre-processor directive while enum is part of the actual C language. #define statements are processed by the compiler before the first line of C code is even looked at!


3 Answers

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;
like image 102
Chris Lutz Avatar answered Oct 16 '22 10:10

Chris Lutz


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++

like image 4
Shaded Avatar answered Oct 16 '22 11:10

Shaded


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.

like image 3
abelenky Avatar answered Oct 16 '22 12:10

abelenky