The standard way of declaring an enum in C++ seems to be:
enum <identifier> { <li开发者_开发技巧st_of_elements> };
However, I have already seen some declarations like:
typedef enum { <list_of_elements> } <identifier>;
What is the difference between them, if it exists? Which one is correct?
C compatability.
In C, union
, struct
and enum
types have to be used with the appropriate keyword before them:
enum x { ... };
enum x var;
In C++, this is not necessary:
enum x { ... };
x var;
So in C, lazy programmers often use typedef
to avoid repeating themselves:
typedef enum x { ... } x;
x var;
I believe the difference is that in standard C if you use
enum <identifier> { list }
You would have to call it using
enum <identifier> <var>;
Where as with the typedef around it you could call it using just
<identifier> <var>;
However, I don't think it would matter in C++
Similar to what @Chris Lutz said:
In old-C syntax, if you simply declared:
enum myEType { ... };
Then you needed to declare variables as:
enum myEType myVariable;
However, if you use typedef:
typedef enum { ... } myEType;
Then you could skip the enum-keyword when using the type:
myEType myVariable;
C++ and related languages have done away with this restriction, but its still common to see code like this either in a pure C environment, or when written by a C programmer.
精彩评论