Union is a user-defined data type-like structure and it can also contain members of different data types. The syntax used for definition, declaration, and for accessing the members in the union is similar to that used in structures, but here keyword union is used instead of the struct keyword. This article explains what a union is and how to write a union program in C using examples and explanations.
The main difference between structure and union is in how memory is allocated to the members. In a structure, each member has its memory location, whereas members of a union share the same memory location.
When a variable of type union is declared, the compiler allocates sufficient memory to hold the largest member in the union. Since all members share the same memory location, we can use only one member at a time. Thus, the union is used for saving memory.
The concept of union is useful when not all member variables are needed simultaneously. The union can hold only one value at a time.
This program illustrates the concept of unions.
1. Define the union.
2. Take the input and store it in the variable using dot operator.
3. Print the output using dot operator and exit.
Let’s discuss the concept of different types of unions in the C language.
- Diagrammatic Representation of Union
- Defining Union in C
- Declaring/Initializing Union Variable
- Accessing Members of Union Type
- Memory Distribution/Consumption in Union Variable
- Address Locations of Union Type Variable and its Member
- Nesting of Unions
- An Array of Unions
- Typedef in Union
union tag { double first; int second; char third; };
A union has to be defined before we use it in our program.
Syntax of the definition of a union is the following:
keyword tag name | / | / | / union union_name { datatype member 1; datatype member 2; ………data type member n; };
We can declare union variables either at union definition or separately using the union keyword along with the tag name.
Type1:
union union_name { datatype member 1; datatype member 2; ………data type member n; }variable_1,variable_2;
Type 2:
union union_name variable_1, variable_2;
Type 1: Union using Dot Operator (*Membership Operator)
We can access the union members using the same syntax used for structures. If we have a union variable the members can be accessed using the dot(.) operator.
Here is source code of the C program to illustrate the concept of unions using dot operator. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C program to illustrate the concept of unions using dot operator
*/
#include<stdio.h>
int main()
{
#include <stdio.h>
//scope of union -> main function
void main()
{
union number
{
int n1;
float n2;
};
//initializing union number variable by using union keyword and tag name
union number x;
printf("Enter the value of n1: ");
scanf("%d", &x.n1); //access using dot product
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);
}
1. Define the union named number with two variables n1 and n2.
2. Define the union variable x.
3. Take the value of two variables using dot operator(i.e. x.n1, x.n2) as input.
4. Print the values of two variables using dot operator as output.
Enter the value of n1: 10 Value of n1 = 10 Enter the value of n2: 50 Value of n2 = 50.000000
Type 2: Union using dereference Operator (->)
-> means ‘dereference and access member’.
a->b is equivalent to (*a).b
Here is source code of the C program to illustrate the concept of unions using dereference operator. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C program to illustrate the concept of unions using dereference operator
*/
#include<stdio.h>
int main()
{
//scope of union -> main function
union student{
int marks;
char section;
}manushi, arjun;//initializing union student variable at union declaration.
//declaring a pointer of student type union.
union student *stud;
//assigning the address of manushi a variable to stud pointer.
stud = &manushi;
stud->marks = 20;
printf("%d\n", stud->marks);
stud->section='a';
printf("%c\n", stud->marks);
return 0;
}
1. Define the union named student with two variables marks and section.
2. Initializing union student variable (manushi, arjun) at union declaration.
3. Define the union variable stud.
4. Assigning the address of manushi a variable to stud pointer.
5. Print the values of manushi and section as output.
Output: 20 a
Here is source code of the C program to illustrate the Memory distribution/consumption in union variable. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C program to illustrate the Memory distribution/consumption in union variable
*/
#include<stdio.h>
int main()
{
//scope of union -> main function
union student
{
int marks;
char section;
} arjun;
//initializing union student variable at union declaration.
arjun.section='b';
printf("%d",sizeof(arjun));
return 0;
}
1. Int marks => 4 bytes and Char section => 1 byte.
2. arjun variable has a total of 4 bytes as memory as it has an int type variable marks and a char type variable section whose memory consumption is 4 bytes and 1 byte respectively.
3. Union type gets memory equal to the highest memory holding member variable, which here are marks having memory equal to 4 bytes thus arjun has 4 bytes of memory which is shared with both of its member variables.
4
Here is source code of the C program to get the address locations of union type variable and its member. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C program to get the address locations of union type variable
*/
#include<stdio.h>
int main()
{
//scope of union -> main function
union student
{
int marks;
char section;
} arjun;//initializing union student variable at union declaration.
arjun.section='b';
printf("Address of union variable arjun: %p \t",&arjun);
printf("Size of union variable arjun: %d \n",sizeof(arjun));
printf("Address of arjun's member variable marks: %p\t",&arjun.marks);
printf("Size of union variable's member variable marks: %d \n",sizeof(arjun.marks));
printf("Address of arjun's member variable section: %p\t",&arjun.section);
printf("Size of union variable's member variable section: %d \n",sizeof(arjun.section));
return 0;
}
1. Int marks => 4 bytes and Char section => 1 byte.
2. Initializing union student variable at union declaration.
3. arjun variable has a total of 4 bytes as memory as it has an int type variable marks and a char type variable section whose memory consumption is 4 bytes and 1 byte respectively.
4. Assign the value using dot operator(i.e. arjun.section=’b’).
5. Print the address and size of union variables.
Address of union variable arjun: 000000000061FE1C Size of union variable arjun: 4 Address of arjun's member variable marks: 000000000061FE1C Size of union variable's member variable marks: 4 Address of arjun's member variable section: 000000000061FE1C Size of union variable's member variable section: 1
A structure may be nested in a union or a union can be nested in a structure based on the requirement. Unions save memory, by giving only that much memory which is needed for its biggest element/member variable.
Here is a great example of how to use unions in your program to save memory.
Here is source code of the C program to illustrate the use of Nesting of unions. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C program to illustrate the use of Nesting of unions
*/
#include<stdio.h>
#include<stdlib.h>
int main()
{
int i;
struct employee_imfo
{
int employee_id;
union
{
long int adhar_card_number;
long int voter_id_card_number;
char other_id [8];
};
char goverment_id;
}a,b,c;
a.employee_id = 8;
a.goverment_id='a';
a.adhar_card_number = 868796;
b.employee_id=7;
b.goverment_id='v';
b.voter_id_card_number = 1234;
printf("Employee a Information :\n");
if(a.goverment_id=='a')
{
printf("GOVT. ID PROVIDED IS ADHAR CARD_ID\n");
}
else
{
printf("GOVT. ID PROVIDED IS VOTER ID CARD\n");
}
printf("a id :%d\na's government provided id %d", a.employee_id,a.adhar_card_number);
printf("\n\n");
if(b.goverment_id=='a')
{
printf("GOVT. ID PROVIDED IS ADHAR CARD_ID\n");
}
else
{
printf("GOVT. ID PROVIDED IS VOTER ID CARD\n");
}
printf("Employee b Information :\n");
printf("b id :%d\nb's government provided id %d", b.employee_id,b.voter_id_card_number);
printf("\n\n");
printf("size of structure variable a %d", sizeof(a));
return 0;
}
Note: Here we used an unnamed union that takes only 8 bytes of spaces if we have not nested union in the structure we might have used more space in our program.
Employee a Information: GOVT. ID PROVIDED IS ADHAR CARD_ID a id: 8 a's government provided id 868796 GOVT. ID PROVIDED IS VOTER ID CARD Employee b Information: b id: 7 b's government provided id 1234 size of structure variable a 12
We can also declare an array of unions that can store data in continuous form and provide options to choose any one of the member variables in an element in the array.
Here is source code of the C program demonstrating the use of union arrays. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C program demonstrating the use of union arrays.
*/
#include<stdio.h>
union tenthClassPerformances
{
int totalmarks;
char grade;
};
int main()
{
union tenthClassPerformances marks[5];
marks[0].totalmarks=90;
marks[1].totalmarks=12;
marks[2].grade='d';
marks[3].grade='f';
marks[4].totalmarks=65;
printf("%d \n",marks[0].totalmarks);
printf("%d \n",marks[1].totalmarks);
printf("%c \n",marks[2].grade);
printf("%c \n",marks[3].grade);
printf("%d \n",marks[4].totalmarks);
return 0;
}
90 12 d f 65
The type definition facility allows us to define a new name for an existing data type.
General Syntax of Typedef in Union
typedef data_type alias;
Here, typedef is a keyword.
data-type is any existing data type or user defined data types such as structures or unions.
alias is identifier that can be used instead of using the name of the particular data-type.
Here is source code of the C program demonstrating the Typedef in union. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C program demonstrating the Typedef in union
*/
#include<stdio.h>
union tenthClassPerformances
{
int totalmarks;
char grade;
};
int main()
{
typedef union tenthClassPerformances performance;
performance steve;
performance virat;
steve.grade='A';
virat.totalmarks= 56;
printf("%c %d",steve.grade,virat.totalmarks);
return 0;
}
1. Define the union named tenthClassPerformances with two variables totalmarks and grade.
2. If we did not utilise the typedef keyword, we would have to write
union tenthClassPerformances virat;
union tenthClassPerformances steve;
Which becomes lengthy and hard to read hence we used typedef to make it look better.
3. typedef makes our program more portable. When program is run on a different machine on which standard data types are represented by different number of bytes, only typedef statement has to be changed.
A 56
To practice programs on every topic in C, please visit “Programming Examples in C”, “Data Structures in C” and “Algorithms in C”.
- Watch Advanced C Programming Videos
- Apply for C Internship
- Practice BCA MCQs
- Practice Computer Science MCQs
- Check Computer Science Books