Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ typedef enum and just enum [duplicate]

Tags:

c++

typedef

What exactly is the difference between:

typedef enum {
  something1,
  something2,
  .....
  somethingN
} myEnum;

end just

enum myEnum{
  something1,
  something2,
  .....
  somethingN
};

I know in first case I have typedefed unnamed enum, of course, just wonder which approach is better and why?

like image 646
Nickoleta Dimitrova Avatar asked Mar 27 '12 15:03

Nickoleta Dimitrova


People also ask

Can we use typedef with 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 { //...

What is the difference between typedef enum and enum in C?

enum defines a type name automatically, While in case of typedef we define a new data type which may be of any kind of data type so that we do not have declare it explicitly everytime.

Can you have 2 enums the same value?

CA1069: Enums should not have duplicate values.

Do I need typedef for enum in C?

Typedefs for enums, structs and unions are a complete waste. They hide important information for the questionable benefit of saving a few characters to type. Don't use them in new code.


3 Answers

The first variant was useful in C, because otherwise you would have to write enum myEnum everywhere you wished to use it.

This is not the case in C++. So, AFAIK, there is no benefit to the first case in C++ (unless you're defining e.g. an interface that needs to be shared with C).

like image 162
Oliver Charlesworth Avatar answered Oct 15 '22 06:10

Oliver Charlesworth


No difference. In fact, the first version is C-style coding.

C++11 has introduced stronly-typed enum, which you define as:

enum class myEnum  //note the 'class' keyword after the 'enum' keyword
{   
  something1,
  something2,
  .....
  somethingN
};

In C++03, enums are not type-safe, they're essentially integers, and can mix with other integral types implicitly, and another problem with them is that they don't have scope; you can use its member without qualifying its type; you can use something1. Whereas C++11 strongly-typed enums are type-safe, and they've scope; you've to use myEnum::something1.

like image 30
Nawaz Avatar answered Oct 15 '22 05:10

Nawaz


I wouldn't use the first one. It is almost the same as the other one. In C++11, with the second you can write myEnum::something1 but not with the first one. Also in C++11, you can forward declare enums in some cases, but it is impossible to do forward declarations of unamed types and you can't forward declare typedefs either.

like image 21
R. Martinho Fernandes Avatar answered Oct 15 '22 06:10

R. Martinho Fernandes