C Union
C Union
In C, a union is a special data type that allows you to store different data types in the same memory
location. A union can contain multiple members, but only one member can hold a value at any given time.
This is useful for memory efficiency, as the union uses the size of its largest member.
Here,
var1 is a union variable.
member1 is a member of the union.
memberA is a member of member1.
Initialization of Union in C
The initialization of a union is the initialization of its members by simply assigning the value to it.
var1.member1 = some_value;
Key Points
1. Memory Size: The size of a union is determined by the size of its largest member.
2. Shared Memory: All members share the same memory location, so changing one member's value
affects the others.
3. Use Cases: Unions are often used in scenarios where a variable can take on multiple types, such as in
embedded programming or when interfacing with hardware.
Example1:
#include <stdio.h>
union Job {
float salary;
int workerNo;
} j;
int main() {
j.salary = 12.3;
// when j.workerNo is assigned a value, j.salary will no longer hold 12.3
j.workerNo = 100;
printf("Salary = %.1f\n", j.salary);
printf("Number of workers = %d", j.workerNo);
return 0;
}
Output:
Salary = 0.0
Number of workers = 100
// Define a union
union Data {
int num;
char ch;
};
int main() {
// Declare a union variable
union Data data;
num: 100
ch: A
Size of union is equivalent to the size of the Size of the structure is > to the sum of
Size
member having largest size. the each member’s size.
Member At a time, only one member of union can be Members of structure can be accessed
Access accessed. individually at any time.