Reputation: 146
What is the difference between following 2 enum declarations in C ?
typedef enum colour
{ Red, Blue
};
typedef enum colour
{ Red,Blue
}colour;
//in your response please refer to this colour as colour2 to avoid confusion
Upvotes: 2
Views: 3087
Reputation: 455
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
Upvotes: 0
Reputation: 6121
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
Upvotes: 3
Reputation: 538
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.
Upvotes: 0