Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the benefits of unnamed structs / unions in C?

Tags:

c

struct

unions

I found one code implemented as the similar demo shown below ..

struct st
{
 int a;
 struct
 {
 int b;
 };
};

6.58 Unnamed struct/union fields within structs/unions

As permitted by ISO C11.

But What are benefits of it ?

Because anyway I can access the data members in a same manner like

int main()
{
 struct st s;
 s.a=11;
 s.b=22;
 return 0;
}

compiled on gcc 4.5.2 with ,

gcc -Wall demo.c -o demo 

and no errors ,

like image 475
Omkant Avatar asked Nov 14 '12 09:11

Omkant


People also ask

What is the use of anonymous structure in C?

In C11 standard of C, anonymous Unions and structures were added. Anonymous unions/structures are also known as unnamed unions/structures as they don't have names. Since there is no names, direct objects(or variables) of them are not created and we use them in nested structure or unions.

What is the difference between a union and an anonymous union?

An anonymous union is a union without a name. It cannot be followed by a declarator. An anonymous union is not a type; it defines an unnamed object. The member names of an anonymous union must be distinct from other names within the scope in which the union is declared.

Can we declare union inside structure?

A structure can be nested inside a union and it is called union of structures. It is possible to create a union inside a structure.

How do you use a struct union?

The unions are basically used for memory saving & it's size is equal to the largest member of the union. And for accessing the data fields of a union, use the dot operator(.) just as you would for a structure and explained by @Atmocreations.


1 Answers

It does not have to be an anonymous struct inside a struct, which I do not find very useful: this will typically only change the layout slightly by introducing more padding, with no other visible effects (compared to inlining the members of the child struct into the parent struct).

I think that the advantage of anonymous struct/unions is elsewhere: they can be used to place an anonymous struct inside an union or an anonymous union inside a struct.

Example:

union u
{
  int i;
  struct { char b1; char b2; char b3; char b4; };
};
like image 143
Pascal Cuoq Avatar answered Sep 27 '22 15:09

Pascal Cuoq