Union in c

In C, union is a collection of different types of data. It means data may be a collection of different data types, i.e. it’s maybe a combination of integers, characters, and floats values. Declaration, and accessing union are the same as structure.

Structure VS Union

Union and structures look alike, but are engaged in totally different activities.

Both structure and unions are used to group a number of different variable together.

A structure enable us treat a number of different variables stored at different places in memory. Union enables us to treat the same space in memory as a number of different variables.

Union offers a way for a section of memory to be treated as a variable of one type on one occasion, and as a different variable of a different type on another occasion.

Syntax of Union in C

The general form or syntax for union is given below:

Union union_name
{
	Type structure_element 1;
	Type structure_element 2;
			---------
			---------	
	Type structure_element n;
};

For example: Below we are going to declare a union named choice having four elements age, id, gender, and salary.

union choice
{
	int age;
	int user_id;
	char gender;
	float salary;
};

Declaration of Union Variable:

For the declaration of union variable first, we write union keyword then we write union name and finally we write union variable like given below.

Union union_name variable_name1,..........;

For example: Below is the declaration of two union variables c1, and c2.

Union choice c1,c2...;

The above declaration of union would occupy 4 bytes for the largest data type that is float.

Accessing union elements: Union element is accessed by using the dot(.) operator with the union variable name. The above union elements can be accessed by

c1.age
c1.user_id
c1.gender
c1.salary

Union Implementation C Program:

Below is a simple program to implement union.

Source Code:

// Union Implementation 
#include <stdio.h>

int main()
{
    union a
    {
        short int i;
        char ch[2];
    };
    
    union a key;
    
    key.i = 512;
    
    printf("Key.i = %d\n",key.i);
    printf("Key.ch[0] = %d\n",key.ch[0]);
    printf("Key.ch[1] = %d\n",key.ch[1]);
    printf("Key.ch[2] = %d\n",key.ch[2]);

    return 0;
}

Output:

Key.i = 512
Key.ch[0] = 0
Key.ch[1] = 2
Key.ch[2] = 0

In the above program we first declared a data type of the type union a, and then a variable key to be of the type union a. Then the union elements are accessed using “.” operator (pronounce as dot operator).

Recommended Post: