Using an anonymous struct vs a named struct with typedef

  • A+
Category:Languages

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.

 


They are pretty much equivalent. Actually, you can use the same name on both places.

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; }; 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: