Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly does this syntax do? (in relation to c-style structs)

Tags:

c

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;
like image 566
John Humphreys Avatar asked Dec 09 '22 03:12

John Humphreys


2 Answers

It defines two typedefs, like:

typedef struct work_tag {
    //contents.
} work_t;

typedef struct work_tag *work_p;
like image 51
asaelr Avatar answered Dec 31 '22 02:12

asaelr


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.

like image 29
Keith Thompson Avatar answered Dec 31 '22 00:12

Keith Thompson