I understand the whole typedef-ing a struct in C concept so that you can avoid using the keyword struct whenever you use it. I'm still a little confused about what's going on here though.
Can someone tell me the various things this structure definition is doing?
typedef struct work_tag {
//contents.
} work_t, *work_p;
It defines two typedefs, like:
typedef struct work_tag {
//contents.
} work_t;
typedef struct work_tag *work_p;
As the other answers say, it defines two typedefs, one named work_t
that refers to struct work_tag
, and another name work_p
that refers to struct work_tag*
.
Note that a typedef
does not create a new type. All it does is create an alias for an existing type. struct work_tag
and work_t
are not two similar types, they're two names for exactly the same type.
Now let's discuss why you'd want to do this.
The types struct work_tag
and struct work_tag*
already have perfectly good names. A typedef
gives you a way to refer to those types using a single identifier, but in my opinion that's really not much of an advantage. And a typedef
for a pointer type can actually be a bit dangerous. If you want to define a name for a truly opaque type, where code that uses it doesn't take advantage of the fact that it's a struct or a pointer, a typedef
is a good solution; otherwise, you're just obscuuring important information.
I'd just write:
struct work {
// contents
};
and then refer to the type as struct work
, and to a pointer to the type as struct work*
.
But if you really feel the need to have a one-word name for the type, there's no need to use different names for the tag and the typedef:
typedef struct work {
// contents
} work;
Now you can refer to the type either as struct work
or as work
, and to the pointer type either 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 can't use the typedef name inside the definition; the typedef name doesn't become visible until the end of definition.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With