What is Union?

Union in c language is a user defined datatype that is used to hold different type of elements. The union keyword is used to define union.
But it doesn't occupy sum of all members size. It occupies the memory of largest member only. It shares memory of largest member.

Unions are conceptually similar to structures. The syntax to declare/define a union is also similar to that of a structure. The only differences is in terms of storage. In structure each member has its own storage location, whereas all members of union uses a single shared memory location which is equal to the size of its largest data member.

By definition, a union is a type that stores different data types in the same memory location, but not at the same time. A union is a group of data objects that share a single block of memory.




#include <stdio.h>
#include <string.h>
union employee
{ int id;
char name[50];
}e1; //declaring e1 variable for union
int main( )
{
//store first employee information
e1.id=101;
strcpy(e1.name, "itechtuto");//copying string into char array
//printing first employee information
printf( "employee 1 id : %d\n", e1.id);
printf( "employee 1 name : %s\n", e1.name);
return 0;
}

Output :-

employee 1 id : 1869508435
employee 1 name : itechtuto

#include <stdio.h>
#include <string.h>
union item
{
int a;
float b;
char ch;
};
int main( )
{
union item it;
it.a = 12;
it.b = 20.2;
it.ch = 'z';
printf("%d\n", it.a);
printf("%f\n", it.b);
printf("%c\n", it.ch);
return 0;
}

output
-26426
20.1999
z

As you can see here, the values of a and b get corrupted and only variable c prints the expected result. This is because in union, the memory is shared among different data types. Hence, the only member whose value is currently stored will have the memory.
In the above example, value of the variable c was stored at last, hence the value of other variables is lost.





Previous Next

Trending Tutorials




Review & Rating

0.0 / 5

0 Review

5
(0)

4
(0)

3
(0)

2
(0)

1
(0)

Write Review Here


Ittutorial