Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

enums

typedef

I had code 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.

like image 680
mmr Avatar asked Sep 29 '10 00:09

mmr


People also ask

What is the use of typedef enum in C?

Using the typedef and enum keywords we can define a type that can have either one value or another. It's one of the most important uses of the typedef keyword. This is the syntax of an enumerated type: typedef enum { //...

Do I need typedef for enum in C?

The typedef keyword is used to name user-defined objects. Structures often have to be declared multiple times in the code. Without defining them using typedef each declaration would need to start with the struct / enum keyword, which makes the code quite overloaded for readability.

Why do we use enumeration in C?

Enumeration (or enum) is a user defined data type in C. It is mainly used to assign names to integral constants, the names make a program easy to read and maintain.

What is the difference between typedef and enum in C?

A typedef also allows more strict type-checking than just declaring something with, say, “struct mystruct xxx”. An enum declaration allows new names and “values” to be defined and used in the code. In the days when C didn't have a standard “bool” type, a common enum used to be.


2 Answers

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.

like image 80
Chris Dodd Avatar answered Oct 29 '22 22:10

Chris Dodd


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.

like image 21
Alex Emelianov Avatar answered Oct 29 '22 23:10

Alex Emelianov