I’m curious what the difference here is when typedefing an enum or struct. Is there any difference semantically between these two blocks?
This:
typedef enum { first, second, third } SomeEnum;
and this:
enum SomeEnum { first, second, third };
typedef enum SomeEnum SomeEnum;
Same deal for structs. I’ve seen both in use, and they both seem to do the same thing in C or Objective-C. Is there a real difference or is it just a preference for which style you can use?
The difference is that the second approach declares a type named
enum SomeEnumand also declares a typedef-nameSomeEnum– an alias for that type. It can actually be combined into the equivalent one-linerwhich makes it rather obvious that the only difference between the two approaches is whether there’s a name after the
enumkeyword. With the second approach, you can declare object of that enum type by using eitherSomeEnum eorenum SomeEnum e, whichever you prefer.The first approach only declares the typedef-name
SomeEnumfor an originally anonymous enum type, meaning that you are limited toSomeEnum edeclarations.So, as long as you only use the typedef-name
SomeEnumin your declarations, there will be no difference between the two. However, in some cases you might have to use the full original name of the typeenum SomeEnum. In the first approach that name is not available, so you’ll be out of luck.For example, if after the above declaration you also declare a variable named
SomeEnumin some nested scopethe name of the variable will hide the typedef-name of the enum, thus making this declaration illegal
However, if you used the second approach when declaring your enum, you can work around this problem by using the full type name
This would not be possible if you used the first approach when declaring your enum type.
When used with structs, the name after the
structis a must when you need a self-referencing type (a type that contains a pointer to the same type), likeFinally, in the second approach the typedef name is totally optional. You can simply declare
and just use
enum SomeEnumevery time you need to refer to this type.