4

After I declare

enum color {red, blue, green};

is there any difference between

color a=blue;

and

enum color a=blue;
2
  • 3
    More of a C thing, really. It's the same deal as struct. Commented Jun 21, 2013 at 19:52
  • color a=blue; won't work if you've done something like: enum color{blue} color;. In that case you need enum color a=blue; to distinguish between the object and the type. Of course you should simply not overload the enum name this way. Commented Jun 21, 2013 at 20:04

3 Answers 3

9
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 };
Sign up to request clarification or add additional context in comments.

Comments

5

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.

3 Comments

Hi i tried your code but get an error:error: type 'main()::color' with no linkage used to declare function 'main()::color color(const char*)' with linkage [-fpermissive]|. I have no idea what it means.
@focusHard: Move the function definition outside of main (ideone.com/RgWBZx): stackoverflow.com/questions/16053148/…
@focusHard You put this inside a function, in which case enum color is a function-local type that cannot be a parameter of an external function. Generally, while you are allowed to define function-local types, there are restrictions on how those types can be used. I had intended for the code in my answer to be a complete, valid translation unit.
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.