Type an enumeration type as a structure

nested here. One of our partners sent us prototypes of the library API functions that they use. There is an enumeration like:

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

The enumeration type is then entered as a structure:

 typedef struct status status_t; 

What is the meaning of this typedef? Does this have any practical significance? Should I treat it like a regular structure? I think that despite this approach, I can convert the enumerator to a structure, and I can access a member of the structure, but I'm not sure. Any hint would be greatly appreciated. Reference Edition L.

On arm-gcc, GNU c99

+5
source share
2 answers

These are two different types.

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

The fact that the typedef name assigned to the enumeration matches the tag name specified for the structure does not mean that they are in any way related to the compiler.

+5
source

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 name of type status is different from the name of the status participant and the struct status tag. Somewhere in the code above, or maybe not included, but necessary, this is a separate definition of the structure, also called status .

In C, a native struct tag is not a type identifier, so there is no ambiguity. struct status not the same type as an alias of the status enumeration type. This is not necessarily a good idea, but it is not invalid. Of course, this would be a mistake if C ++ compilation was used, because then for struct status , status would be a type name, therefore, I would encounter the status enumeration alias.

+3
source

Source: https://habr.com/ru/post/1275453/


All Articles