UNION
C Union is also like structure, i.e. collection of different data types which are grouped together. Each element in a union is called member.
Union and structure both are same, except allocating memory for their members. Structure allocates storage space for each member separately. Whereas, Union allocates one common storage space for all its members.
Syntax
union tag_name
{
data type var_name1;
data type var_name2;
data type var_name3;
};
Example
union student
{
int id;
char name[10];
char address[50];
};
Initializing and Declaring union variable
union student data;
union student data = {001,''AKKI'', ''mumbai''};
Accessing union members
data.id
data.name
data.address
Union and structure both are same, except allocating memory for their members. Structure allocates storage space for each member separately. Whereas, Union allocates one common storage space for all its members.
Syntax
union tag_name
{
data type var_name1;
data type var_name2;
data type var_name3;
};
Example
union student
{
int id;
char name[10];
char address[50];
};
Initializing and Declaring union variable
union student data;
union student data = {001,''AKKI'', ''mumbai''};
Accessing union members
data.id
data.name
data.address
1.Union is approximately same as structure but it does not support multiple values simultaneously .
2.It supports only one value at a time.
3.It always supports last value.
4.In given example only makes will be true because marks is the last value assigned to it.
#include<stdio.h>
#include<string.h>
union Student
{
char name[200];
int rollno;
float marks;
};
int main()
{
union Student obj;
strcpy(obj.name,"Anil Singhania");
obj.rollno=205;
obj.marks=86.4;
printf("Name=%s\n",obj.name);
printf("Rollno=%d\n",obj.rollno);
printf("Marks=%f\n",obj.marks);
}
•Output
Name =temple
Roll no.=temple
Marks =86.4
Comments