C - Union

Learn C - C tutorial - C union - C examples - C programs
C Union - Definition and Usage
- Union and structure in C - Programming are same in concepts, except allocating memory for their members.
- Structure allocates storage space for all its members separately.
- Whereas, Union allocates one common storage space for all its members.
- We can access only one member of union at a time.
- We can’t access all member values at the same time in union.
- But, structure can access all member values at the same time.
- This is because, Union allocates one common storage space for all its members. Whereas Structure allocates storage space for all its members separately.

C Syntax
union tag_name
{
data type var_name1;
data type var_name2;
data type var_name3;
};
Sample - C Code
#include <stdio.h>
#include <conio.h>
{
union number
{
int n1;
float n2;
};
void main()
union number x;
clrscr();
printf("Enter the value of n1: ");
scanf("%d", &x.n1);
printf("Value of n1 =%d", x.n1);
printf("\nEnter the value of n2: ");
scanf("%f", &x.n2);
printf("Value of n2 = %f\n",x.n2);
getch();
}
C Code - Explanation

- In this statement we create the union with its union name as “number” where the union contain different data types.
- Here in this statement we create a variable for accessing a union element whose union variable name is “x” .
- In this statement we get the value for the variable “n1” with its union variable name by printing the value.
- In this statement we get the value for the variable “n2” with its union variable name by printing the value.
Sample Output - Programming Examples

- Here in this output we get the integer value for the variable “n1” where its value “24” has been displayed here.
- Here in this output we get the float value for the variable “n2” where its value “34.500000” has been displayed here..