Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typedefine an enum type as structure

embedded c here. One of our partners sent us the API prototypes of the library functions they are using. There is an enum like :

typedef enum{
     val1 = 0, 
     val2 = 1, 
    [..]
} status;

The enum type is then typedefined as a structure:

typedef struct status status_t;

What's the meaning of this typedef? Has it some practical meaning? Do I have to handle it like a regular structure? I think that whit this approach I can convert an enumerator to a structure and I can access a member of the structure, but I am not sure. Any hint would be very appreciated. B.R. L.

On arm-gcc, GNU c99

like image 261
Catosh Avatar asked Feb 19 '18 13:02

Catosh


2 Answers

These are two different types.

Structure names are in their own namespace. So struct status is different from status. The former is the name of a structure, while the latter is a typedef which refers to an unnamed enum.

The fact that the typedef name assigned to an enum is the same as the tag name given to a struct does not mean they are associated in any way as far as the compiler is concerned.

like image 186
dbush Avatar answered Oct 04 '22 20:10

dbush


Consider the following valid code:

typedef enum
{
     STATUS1 = 0, 
     STATUS2 = 1
} status ;


// struct tag
//         |
//         V
struct status
{
    status status ;
    //  ^    ^
    //  |    |_______
    //  |           |
    // type_name  member_name
} ;

typedef struct status status_t ;
//                       ^
//                       |
//                      Type alias
int main()
{

    // The following is valid    
    status_t status_structure ;
    status_structure.status = STATUS1 ;

    // So is this    
    struct status status ;
    status.status = STATUS1 ;


    return 0;
}

The type name status is distinct from both the member name status and the struct tag status. Somewhere in the code given, or possibly not included but necessary, is a separate definition of a struct also called status.

In C, the struct tag on its own is not a type identifier, so there is no ambiguity struct status is not the same type as the enum type alias status. It is not necessarily a good idea, but it is not invalid. It would of course fail if C++ compilation were used because then for struct status, status would be a type name, so would clash with the enum alias status.

like image 42
Clifford Avatar answered Oct 04 '22 22:10

Clifford