When should one of the following statements be used over the other?
typedef struct Foo { int a; } Bar;
and
typedef struct { int a; } Bar;
and use it like
Bar bar1 = { 5 };
I understand the second on is an anonymous struct but not sure when should one be used over the other.
Basically struct is used to define a structure. But when we want to use it we have to use the struct keyword in C. If we use the typedef keyword, then a new name, we can use the struct by that name, without writing the struct keyword.
PLEASE don't typedef structs in C, it needlessly pollutes the global namespace which is typically very polluted already in large C programs. Also, typedef'd structs without a tag name are a major cause of needless imposition of ordering relationships among header files.
You can't "typedef a struct", that doesn't mean anything.
The C language contains the typedef keyword to allow users to provide alternative names for the primitive (e.g., int) and user-defined (e.g struct) data types. Remember, this keyword adds a new name for some existing data type but does not create a new type.
They are pretty much equivalent. Actually, you can and should use the same name on both places. Use the same name unless you can come up with a good reason not to.
One situation where you want the non-anonymous is when you want pointers to an object of the same type, like in a linked list.
typedef struct Node { struct Node* next; int data; } Node;
One alternative:
typedef struct Node Node; struct Node { Node * next; int data; };
According to Linus Torvalds, you should avoid typedefing structs unless you want to hide it. From the Linux kernel coding style guide:
Please don’t use things like vps_t. It’s a mistake to use typedef for structures and pointers. When you see a
vps_t a;
in the source, what does it mean? In contrast, if it saysstruct virtual_container *a;
you can actually tell what a is.Lots of people think that typedefs help readability. Not so. They are useful only for:
a) totally opaque objects (where the typedef is actively used to hide what the object is).
...
According to that, you should never use anonymous structs, and the typedefs are strictly for interfaces. So it should look like this:
typedef struct Node { struct Node* next; int data; } Node;
But if you are really creating an interface, you should in general separate it into a header file and a source file. In this case, put the typedef in the header file and do NOT use the typedef:ed type at all in the source file.
.c
struct Node { struct Node* next; int data; } Node; void insert(struct Node* head, int data) { // Code }
.h
typedef struct Node Node; void insert(Node* head, int data);
Taking all of the above into consideration, the only valid situation to use an anonymous struct is if you declare an object at the same time like this:
struct { int data; float more_data; } myObject;
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