开发者

What is the difference between declaring an enum with and without 'typedef'?

开发者 https://www.devze.com 2022-12-28 07:32 出处:网络
The standard way of declaring an enum in C++ seems to be: enum <identifier> { <li开发者_开发技巧st_of_elements> };

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消