The standard way of declaring an enum in C++ seems to be:
enum <identifier> { <list_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?
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 { //...
We can have symbolic names to datatypes using typedef but not to numbers etc. Whereas with a macro, we can represent 1 as ONE, 3.14 as PI and many more. We can have a type name and a variable name as same while using typedef. Compiler differentiates both.
Enum is to define a collection of options available. A struct can contain both data variables and methods. Enum can only contain data types. A struct supports a private but not protected access specifier.
One of the differences between the two is that #define is a pre-processor directive while enum is part of the actual C language. #define statements are processed by the compiler before the first line of C code is even looked at!
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.
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