Variable declaration in C usually means that you have to highlight the datatype and its size to the compiler. This limits you to one data type at a time. However, union is a distinct data type in C that lets you store variables of different data types in the same memory location. Unions are defined similarly to structs. This is shown below:
union UnionName{ //union tag
datatype variable_name;
datatype variable_name;
datatype variable_name;
}UnionVariable; //union variable
Union has multiple members that are each of a different data type. However, only one member contains a value at any given time. Hence, a union variable’s size is as big as the biggest member in its declaration.
Below is an example that demonstrates how only one member holds a value at a time as one.i
prints a garbage value after a float value is stored in one.j
:
#include <stdio.h>union Example{ //union tagint i; //union memberfloat j;}one; //union variableint main() {one.i = 10;one.j = 20.2;//union members can be accessed using (.) operatorprintf("variable i: %d\n", one.i);printf("variable j: %f\n", one.j);return 0;}
The example below demonstrates that the size of a union variable is equal to the largest member:
#include <stdio.h>union Example { //union tagint i; //union memberfloat j;char s[20];}one;int main() {union Example one; // another way to declare union variableprintf("size of variable one: %ld\n", sizeof(one));return 0;}