C Program to Illustrate the Concept of Unions

What is Union?

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.

Problem Description

This program illustrates the concept of unions.

Problem Solution

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.

advertisement
advertisement

Diagrammatic Representation of Union:
union tag
{
    double first;
    int second;
    char third;
};

Union Example

Note: Join free Sanfoundry classes at Telegram or Youtube
Defining Union:

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;
};

Declaring/Initializing Variable:

We can declare union variables either at union definition or separately using the union keyword along with the tag name.

advertisement

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;

advertisement
Method 1: Accessing Members of Union Type


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.

Program/Source Code

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.

  1. /*
  2.  * C program to illustrate the concept of unions using dot operator
  3.  */
  4.  
  5. #include<stdio.h>
  6. int main()
  7. {
  8. #include <stdio.h>
  9. //scope of union -> main function 
  10. void main()
  11. {
  12.     union number
  13.     {
  14.         int  n1;
  15.         float n2;
  16.     };
  17.     //initializing union number variable by using union keyword and tag name
  18.     union number x;
  19.  
  20.     printf("Enter the value of n1: ");
  21.     scanf("%d", &x.n1); //access using dot product
  22.     printf("Value of n1 = %d", x.n1);
  23.     printf("\nEnter the value of n2: ");
  24.     scanf("%f", &x.n2);
  25.     printf("Value of n2 = %f\n", x.n2);
  26. }
Program Explanation

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.

Runtime Test Cases
 
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

Program/Source Code

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.

  1. /*
  2.  * C program to illustrate the concept of unions using dereference operator
  3.  */
  4.  
  5. #include<stdio.h>
  6. int main()
  7. {
  8. //scope of union -> main function
  9.     union student{
  10.         int marks;
  11.         char section;
  12.     }manushi, arjun;//initializing union student variable at union declaration.
  13.  
  14.     //declaring a pointer of student type union.
  15.     union student *stud;
  16.  
  17.     //assigning the address of manushi a variable to stud pointer.
  18.     stud = &manushi;
  19.     stud->marks = 20;
  20.     printf("%d\n", stud->marks);
  21.     stud->section='a';
  22.     printf("%c\n", stud->marks);
  23.     return 0;
  24. }
Program Explanation

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.

Runtime Test Cases
 
Output:
20
a

Method 2: Memory Distribution/Consumption in Union Variable
Program/Source Code

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.

  1. /*
  2.  * C program to illustrate the Memory distribution/consumption in union variable
  3.  */
  4.  
  5. #include<stdio.h>
  6. int main()
  7. {
  8.     //scope of union -> main function
  9.     union student
  10.     {
  11.         int marks;
  12.         char section;
  13.     } arjun;
  14.     //initializing union student variable at union declaration.
  15.  
  16.     arjun.section='b';
  17.     printf("%d",sizeof(arjun));
  18.  
  19.     return 0;
  20. }
Program Explanation

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.

Program Output:
 
4

Method 3: Address Locations of Union Type Variable and its Member
Program/Source Code

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.

  1. /*
  2.  * C program to get the address locations of union type variable
  3.  */
  4.  
  5. #include<stdio.h>
  6. int main()
  7. {
  8.     //scope of union -> main function
  9.     union student
  10.     {
  11.         int marks;
  12.         char section;
  13.     } arjun;//initializing union student variable at union declaration.
  14.  
  15.     arjun.section='b';
  16.     printf("Address of union variable arjun: %p \t",&arjun);
  17.     printf("Size of union variable  arjun: %d \n",sizeof(arjun));
  18.  
  19.     printf("Address of arjun's member variable marks: %p\t",&arjun.marks);
  20.     printf("Size of union variable's member variable marks:  %d \n",sizeof(arjun.marks));
  21.  
  22.     printf("Address of  arjun's member variable section: %p\t",&arjun.section);
  23.     printf("Size of union variable's member variable section:  %d \n",sizeof(arjun.section));
  24.  
  25.     return 0;
  26. }
Program Explanation

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.

Program Output:
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

Method 4: Nesting of Unions

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.

Program/Source Code

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.

  1. /*
  2.  * C program to illustrate the use of Nesting of unions
  3.  */
  4.  
  5. #include<stdio.h>
  6. #include<stdlib.h>
  7. int main()
  8. {
  9.  
  10.     int i;
  11.     struct employee_imfo
  12.     {
  13.         int employee_id;
  14.         union
  15.         {
  16.             long int adhar_card_number;
  17.             long int voter_id_card_number;
  18.             char other_id [8];
  19.         };
  20.         char goverment_id;
  21.     }a,b,c;
  22.  
  23.     a.employee_id = 8;
  24.     a.goverment_id='a';
  25.     a.adhar_card_number = 868796;
  26.  
  27.     b.employee_id=7;
  28.     b.goverment_id='v';
  29.     b.voter_id_card_number = 1234;
  30.  
  31.     printf("Employee a Information :\n");
  32.     if(a.goverment_id=='a')
  33.     {
  34.         printf("GOVT. ID PROVIDED IS ADHAR CARD_ID\n");
  35.     }
  36.     else
  37.     {
  38.         printf("GOVT. ID PROVIDED IS VOTER ID CARD\n");
  39.     }
  40.  
  41.     printf("a id :%d\na's government provided id %d", a.employee_id,a.adhar_card_number);
  42.     printf("\n\n");
  43.  
  44.     if(b.goverment_id=='a')
  45.     {
  46.         printf("GOVT. ID PROVIDED IS ADHAR CARD_ID\n");
  47.     }
  48.     else
  49.     {
  50.         printf("GOVT. ID PROVIDED IS VOTER ID CARD\n");
  51.     }
  52.  
  53.     printf("Employee b Information :\n");
  54.     printf("b id :%d\nb's government provided id %d", b.employee_id,b.voter_id_card_number);
  55.     printf("\n\n");
  56.  
  57.     printf("size of structure variable a %d", sizeof(a));
  58.     return 0;
  59.  
  60. }

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.

Program Output:
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

Method 5: An Array of Unions

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.

Program/Source Code

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.

  1. /*
  2.  * C program demonstrating the use of union arrays.
  3.  */
  4.  
  5. #include<stdio.h>
  6.  
  7. union tenthClassPerformances
  8. {
  9.     int totalmarks;
  10.     char grade;
  11. };
  12. int main()
  13. {
  14.  
  15.     union tenthClassPerformances marks[5];
  16.  
  17.     marks[0].totalmarks=90;
  18.     marks[1].totalmarks=12;
  19.     marks[2].grade='d';
  20.     marks[3].grade='f';
  21.     marks[4].totalmarks=65;
  22.  
  23.     printf("%d \n",marks[0].totalmarks);
  24.     printf("%d \n",marks[1].totalmarks);
  25.     printf("%c \n",marks[2].grade);
  26.     printf("%c \n",marks[3].grade);
  27.     printf("%d \n",marks[4].totalmarks);
  28.  
  29.     return 0;
  30. }
Program Output:
90
12
d
f
65

Method 6: Typedef in Union

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.

Program/Source Code

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.

  1. /*
  2.  * C program demonstrating the Typedef in union
  3.  */
  4.  
  5. #include<stdio.h>
  6.  
  7. union tenthClassPerformances
  8. {
  9.     int totalmarks;
  10.     char grade;
  11. };
  12. int main()
  13. {
  14.     typedef union tenthClassPerformances performance;
  15.     performance steve;
  16.     performance virat;
  17.  
  18.     steve.grade='A';
  19.     virat.totalmarks= 56;
  20.  
  21.     printf("%c %d",steve.grade,virat.totalmarks);
  22.  
  23.     return 0;
  24. }
Program Explanation

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.

Program Output:
A   56

To practice programs on every topic in C, please visit “Programming Examples in C”, “Data Structures in C” and “Algorithms in C”.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.