2

What is the difference between following 2 enum declarations in C ?

  1. typedef enum colour { Red, Blue };

  2. typedef enum colour { Red,Blue }colour; //in your response please refer to this colour as colour2 to avoid confusion

3
  • its either enum colour {Red,Blue}; or type 2 in your question When you use typedef you need to specify the alias of the enumeration. So type 1 is not a valid one. Commented Jan 10, 2013 at 10:17
  • Sorry but i do not understand what you mean...can you explain a bit more. Commented Jan 10, 2013 at 10:18
  • stackoverflow.com/questions/707512/… This will help your for a better understanding of typedef Commented Jan 10, 2013 at 10:25

3 Answers 3

3

In the simplest case, an enumeration can be declared as

enum color {Red,Blue}; 

Any references to this must be preceded with the enum keyword. For example:

enum color color_variable1; // declare color_variable of type 'enum color' enum color color_variable2; 

In order to avoid having to use the enum keyword everywhere, a typedef can be created:

enum color {Red,Blue}; typedef enum color color2; // declare 'color2' as a typedef for 'enum color' 

With typedef, The same variablea can be now declared as

color2 color_variable3; color2 color_variable4; 

FYI, structures in C also follows the similar rules. typedef also makes your code look neater without the C struct(enum) keywords. It can also give logical meanings.

typedef int RADIUS; // for a circle typedef int LENGTH; // for a square maybe though both are int 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Your link explains it well.. stackoverflow.com/questions/707512/…
0

I don't think the first one is correct at all, you don't need the typedef. A named enum is enough; example:

enum colour { Red, Blue }; void myfunc(enum colour argument) { if (argument == Red) { // ... } else { // ... } } 

This is just the same thing you do when you define a named struct.

The second one will define a named enum and map a custom type name colour to that named enum. You could as well make the enum anonymous and only define the custom type name.

1 Comment

Thanks jmc. This link really explains it well: stackoverflow.com/questions/707512/…
0

Actually the simplest example doesn't even need to be named

enum{ Red, //Implicitly 0 Blue //Implicitly 1 }; 

is perfectly acceptable.

Doing this is only for replacing a bunch of #define statements. You don't want to pass an enum shape value where an enum color was expected.

But you can technically use it in the place of an integer, so

int foo(int x){ return x;} int y = foo(Red); 

Will return 0

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.