What exactly does this syntax do? (relative to c-style structures)

I understand the whole typification of structure in the C concept to avoid using the struct keyword whenever you use it. I'm still a little confused about what is going on here.

Can someone tell me the various things this structure definition does?

typedef struct work_tag { //contents. } work_t, *work_p; 
+4
source share
4 answers

It defines two typedefs, for example:

 typedef struct work_tag { //contents. } work_t; typedef struct work_tag *work_p; 
+9
source

As the other answers say, it defines two typedefs, one with the name work_t that references the struct work_tag , and another with the name work_p that refers to the struct work_tag* .

Note that a typedef does not create a new type. All he does is create an alias for the existing type. struct work_tag and work_t are not two similar types, they are two names for the same type.

Now let's discuss why you want to do this.

The types struct work_tag and struct work_tag* already have completely good names. A typedef gives you the ability to refer to these types using a single identifier, but, in my opinion, this is really not very beneficial. A typedef for a pointer type can be a little dangerous. If you want to define a name for a truly opaque type, where the code that uses it does not use the fact that it is a construct or pointer, typedef is a good solution; otherwise, you simply hide important information.

I would just write:

 struct work { // contents }; 

and then refer to the struct work type and the type pointer as struct work* .

But if you really feel the need to have a single-word name for a type, there is no need to use different names for the tag and typedef:

 typedef struct work { // contents } work; 

Now you can refer to the type either as struct work or as work , and to the type of the pointer as struct work* or as work* . (C ++ does this implicitly, C does not.) Note that if a struct work contains a pointer to another struct work , you cannot use the typedef name inside the definition; the typedef name does not become visible until the end of the definition.

+3
source

Think of typedef as a variable declaration. Just as you can make int a, b to make two int variables, you can make typedef int a_t, b_t to make two types in one typedef .

+2
source

Assigning two alternative names to existing types:

 work_t -> struct work_tag work_p -> struct work_tag * 
+1
source

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


All Articles