C ++ Enumeration Syntax

After the announcement

enum color {red, blue, green}; 

is there any difference between

 color a=blue; 

and

 enum color a=blue; 
+4
source share
3 answers
 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 }; 
+9
source

Assuming no other color declaration is available, they mean the same thing. However, a different definition of color does exist, and enum color can be used to make sure this type is used.

 enum color { red, blue, green }; color color(const char *); enum color a = red; 

The second line indicates the return type as color and refers to enum color . The third line requires the enum keyword, because color otherwise refers to the function declared on the second line.

But for practical purposes, enum color and color pretty much mean the same thing.

+5
source

In C (unlike C ++), to create the name color , you must enter typedef enum scolor {red, blue, green} color; or use the definition in the question using enum colour a = blue; - otherwise the compiler will not know what color is.

In C ++, any struct X , class Y or enum Z will automatically be aliases X as struct X and Y as class Y and Z as enum Z - thus reducing the need for typedef struct XX; etc. (although this will still be valid, since C ++ is generally backward compatible with C).

Both forms are equally valid in C ++. This is a matter of style that you prefer.

+2
source

Source: https://habr.com/ru/post/1487553/


All Articles