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?
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 { //...
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.
CA1069: Enums should not have duplicate values.
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.
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).
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With