C Union - Definition, Declaration, Accessing elements

Learn: What is union in C language, how it is declared and defined and how can we access the elements of a union?

Unions can be assumed same as structures but with little difference. Unions can be used to create a data type containing several others data types inside it and we can use an object of that union to access the members inside it.

Below is the declaration for a Union in C:

Union declaration

union tagname
{
	int a;
	char b;
};

Here, union is the keyword to declare a union, tagname is the union name, a and b are the members of the union tagname.

Union variable/object declaration

Now we should create an object for the union in order to access the elements inside it. Below is how we can do that:

union tagname object;

Here, object is the union variable name, that will be used to access the union elements.

Accessing Union elements

Union elements can be accessed using dot (.) operator, use union_variable_name.element_name to access particular element.

object.a= 10;
object.b= 'H';

Till now the union must have looked same as the structures in C. But there is a great difference between structure and the unions. When we create a structure, the memory allocated for it is based on the elements inside the structure. So if a structure has two elements one int and one char than the size of that structure would be at least 5 bytes (if int takes 4 bytes and 1 byte is for char).

In case of the union the size of memory allocated is equal to the size of the element which takes largest size.

So for the union above the size would be only 4 bytes not 5 bytes.

Take the below example:

union tagname
{
	int a;
	char s;
	char t;
};

In this case if we create the object

union tagname object;

Size of this object should be 4 bytes only. This feature of unions gives some benefits but care should be taken while operating with unions. Since the memory allocated is equal to the largest element in the union, values will be overwritten.

Take the below example for better understanding:

#include<stdio.h>
union tagname
{
	int a;
	char s;
	char t;
};

union tagname object;

int main()
{
	object.s='H';
	object.t='E';
	object.a=0xFFFF;

	printf("%c\n",object.s);
	printf("%c\n",object.t);
	printf("%x\n",object.a);

	return 0;
}

Output

�
� 
ffff 

So if the last written element is higher than the size of the previously written elements in the union, than one might not be able to retrieve the values of the previously written values.

Below is the benefit of the union:

#include<stdio.h>

union tagname
{
	int a;
	unsigned char s[4];
};

union tagname object;

int main()
{
	object.a=0xAABBCCDD;
	
	printf("%d\n",sizeof(object));
	printf("%X\n",object.a);
	
	char i;
	for(i=3;i>=0;i--)
		printf("%X\n",object.s[i]);
	return 0;
}

Output

4 
AABBCCDD
AA
BB
CC
DD

Related Tutorials



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.