Reputation: 271
After I declare
enum color {red, blue, green};
is there any difference between
color a=blue;
and
enum color a=blue;
Upvotes: 4
Views: 3511
Reputation:
Assuming no other declaration of color
is available, they mean the same thing. However, it is valid to provide a different definition of color
, and enum color
can be used to make sure the type is used.
enum color { red, blue, green };
color color(const char *);
enum color a = red;
On the second line, specifying the return type as color
is valid, and refers to enum color
. On the third line, the enum
keyword is required, because color
would otherwise refer to the function declared on the second line.
But for practical purposes, enum color
and color
pretty much mean the same thing.
Upvotes: 5
Reputation: 129524
In the C language (as opposed to C++), to create a name color
, you have to type typedef enum scolor {red, blue, green} color;
, or use the definition the question contains, using enum colour a = blue;
- otherwise, the compiler won't know what color
is.
In C++, any struct X
, class Y
, or enum Z
, will automatically alias X
as struct X
and Y
as class Y
and Z
as enum Z
- thus reducing the need to typedef struct X X;
, etc (although this would still be valid, since C++ is, as a whole, backwards compatible with C).
Both forms are equally valid in C++. It's a matter of style which you prefer.
Upvotes: 2
Reputation: 1087
enum MyEnumType { ALPHA, BETA, GAMMA };
enum MyEnumType x; /* legal in both C and C++ */
MyEnumType y; // legal only in C++
enum { HOMER, MARGE, BART, LISA, MAGGIE };
Upvotes: 9