Reputation: 26223
I was getting a little confused with typedef/enum until I realised that I did not need to name the emun. Are there any differences / benefits between these two when used with typedef, the 2nd one to me seems a lot easier to understand.
First Example:
typedef enum enumMenuItems {
none,
add,
save,
load,
list,
remove
} menuItems;
menuItems optionSelect = none;
Second Example:
typedef enum {
Earth = 1,
Mars,
Saturn,
Neptune,
Jupiter
} planets;
planets closest = Mars;
.
typedef enum enumMenuItems {
none,
add,
save,
load,
list,
remove
} menuItems;
So the above essentially defines two types, one an enum called enumMenuItems and the second a typedef of enumMenuItems called menuItems.
menuItems optionSelect = save;
enum enumMenuItems optionSelect = save;
The above two declarations are essentially the same, one using the typedef and the other using the enum. So if your using a typedef you can leave your enum unnamed as the type can be accessed via the typedef menuItem.
gary
Upvotes: 3
Views: 2613
Reputation: 224864
The first case allows you to refer to the type as enum enumMenuItems
. For example:
enum enumMenuTimes optionSelect = none;
It might be clearer if you break it down into two parts:
enum _planets {
Earth = 1,
Mars,
Saturn,
Neptune,
Jupiter
};
typedef enum _planets planets;
enum _planets planet1 = Earth;
planets planet2 = Mars;
If that simplifies the concept for you. Your second notation there is just shorthand; it creates an anonymous enumeration and then uses typedef
to give it a name. You could even, for example, do:
enum {
Value0,
Value1,
Value2
};
But you'd not be able to use the enumeration as a fake type name, like you're trying to do. You can still access the enumerated values, though.
A more in depth description is available at the comp.lang.c FAQ.
Upvotes: 6