Computer >> Computer tutorials >  >> Programming >> C programming

Explain the concept of union of structures in C language


If the structure is nested inside a union, it is called as a union of structures. There is a possibility to create a union inside a structure in C programming language.

Example

Following is the C program for union of structures −

#include<stdio.h>
struct x {
   int a;
   float b;
};
union z{
   struct x s;
};
main ( ){
   union z u;
   u.s.a = 10;
   u.s.b = 30.5;
   printf("a=%d", u.s.a);
   printf("b=%f", u.s.b);
   getch ( );
}

Output

When the above program is executed, it produces the following result −

a= 10
b = 30.5

Example

Given below is another C program for union of structures −

#include<stdio.h>
union abc{
   int a;
   char b;
}v;
int main(){
   v.a=90;
   union abc *p=&v;
   printf("a=%d\n",v.a);//90
   printf("b=%c\n",v.b);//Z
   printf("a=%d b=%c\n",p->a,p->b);//90 Z
   printf("%d",sizeof(union abc));//4
   return 0;
}

Output

When the above program is executed, it produces the following result −

a=90
b=Z
a=90 b=Z
4