开发者

Why should I have an enumeration declared with a typedef in C++?

I had cod开发者_运维百科e that looked like this:

enum EEventID {
  eEvent1,
  eEvent2,
  ...
  eEventN };

And that got reviewed and changed to

typedef enum {
  eEvent1,
  eEvent2,
  ...
  eEventN } EEventID;

What is the difference between the two? Why make the change? When I looked at this question, the only mention of typedefs got downvoted.


The two are identical in C++, but they're not the same in C -- in C if you use the typedef you get code that is compatible between C and C++ (so can be used freely in a header file that might be used for either C or C++). That's the only reason I can see for preferring it.


I found one possible answer here: "Well it is relevent to C language in which if you use an enum or structure which are user defined data types, you need to specify theenum or struct keyword while using it."

Maybe your reviewer is a hardcore C coder, and he does it automatically, out of habit.


If there's a standard at the company, it could just be for consistency. Even if you never use in C, it's still better to do it the same way everywhere.


The typedef is superfluous in C++.
In C it is necessary if you want to define a variable of your enum type like so: EEventID event;, otherwise you would've had to specify it's an enum: enum EEventID event;.


Your reviewer doesn't know his C from his C++.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜