Objective C - when should "typedef" precede "enum", and when should an enum be named?

12,968

Solution 1

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};

Solution 2

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.

Share:
12,968
Scott Pendleton
Author by

Scott Pendleton

I enjoy programming.

Updated on June 03, 2022

Comments

  • Scott Pendleton
    Scott Pendleton almost 2 years

    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 what the enum choices are.