What is a union in C Language?
- The union is a user-defined data type that allows storing multiple types of data in a single unit. However, it doesn’t occupy the sum of the memory of all members. It holds the memory of the largest member only.
- In union, we can access only one variable at a time as it allocates one common space for all the members of a union.
Syntax of union
- union union_name
- {
- Member_variable1;
- Member_variable2;
- .
- .
- Member_variable n;
- }[union variables];
Let’s see a simple example
- #include<stdio.h>
- union data
- {
- int a; //union members declaration.
- float b;
- char ch;
- };
- int main()
- {
- union data d; //union variable.
- d.a=3;
- d.b=5.6;
- d.ch=‘a’;
- printf(“value of a is %d”,d.a);
- printf(“\n”);
- printf(“value of b is %f”,d.b);
- printf(“\n”);
- printf(“value of ch is %c”,d.ch);
- return 0;
- }
Output:
value of a is 1085485921 value of b is 5.600022 value of ch is a
In the above example, the value of a and b gets corrupted, and only variable ch shows the actual output. This is because all the members of a union share the common memory space. Hence, the variable ch whose value is currently updated.
Recent Posts