Objective C - when should "typedef" precede "enum", and when should an enum be named?
In sample code, I have seen this:
typedef enum Ename { Bob, Mary, John} EmployeeName;
and this:
typedef enum {Bob, Mary, John} EmployeeName;
and this:
typedef enum {Bob, Mary, John};
but what compiled successfully for me was this:
enum {Bob, Mary, John};
I put that line in a .h file above the @interface line, and then when I #import that .h file into a different class's .m file, methods there can see the enum.
So, when are the other variants needed?
If I could name the enum something like EmployeeNames, and then, when I type "EmployeeNames" followed by a ".", it would be nice if a list pops up showing wha开发者_C百科t the enum choices are.
In C (and hence Objective C), an enum type has to be prefixed with enum
every time you use it.
enum MyEnum enumVar;
By making a typedef:
typedef MyEnum MyEnumT;
You can write the shorter:
MyEnumT enumVar;
The alternative declarations declare the enum itself and the typedef in one declaration.
// gives the enum itself a name, as well as the typedef
typedef enum Ename { Bob, Mary, John} EmployeeName;
// leaves the enum anonymous, only gives a name to the typedef
typedef enum {Bob, Mary, John} EmployeeName;
// leaves both anonymous, so Bob, Mary and John are just names for values of an anonymous type
typedef enum {Bob, Mary, John};
The names inside enum { }
define the enumerated values. When you give it a name, you can use it as a type together with the keyword enum
, e.g. enum EmployeeName b = Bob;
. If you also typedef
it, then you can drop the enum
when you declare variables of that type, e.g. EmployeeName b = Bob;
instead of the previous example.
Your third example is the same as your last example - the typedef
there is useless - GCC even gives a warning about that case:
warning: useless storage class specifier in empty declaration
Your first and second example are also partly equivalent, in that they both give the enum type a name EmployeeName
. The first example also lets you use enum Ename
interchangeably with EmployeeName
; in the second example, EmployeeName
is the only option. The second example has to be written as you have - you can decompose the first example as follows:
enum Ename { Bob, Mary, John };
typedef enum Ename EmployeeName;
Maybe that helps clear things up?
精彩评论