Union
Union
1
What is Union in C?
Unions in C are a user-defined data type that
permits different data types to be stored in the same
memory location.
While similar to structures, the key difference is
that all members of a union occupy the same
memory location, which means only one member
can store a value at a time.
Unions are primarily used when you need to work
with different data types in the same memory space
to save memory.
2
Union Declaration
In C, you declare a union using the union keyword.
General syntax:
union union_name
{
// member declarations
};
EXAMPLE
union Data {
int i;
float f;
char str[20];
};
3
Different Ways to Define a
Union Variable
There are two ways to define a union variable:
With Union Declaration
union name_of_union {
datatype member;
} var;
This code defines a union named name_of_union with a single member of data
type datatype. The union is named var, and it can hold data of the specified data
type in its member.
After Union Declaration
union name_of_union var;
In this code, name_of_union is the name of an already declared union.
4
Initialization of Union in C
var.member = some_value;
5
Example of Union in C
1. #include <stdio.h> 11. // Assign values to different
2. // Define a union named members of the union
MyUnion 12. data.intValue = 42;
3. union MyUnion { 13. printf("Integer Value: %d\n",
4. int intValue; data.intValue);
5. float floatValue; 14. data.floatValue = 3.14;
6. char stringValue[20]; 15. printf("Float Value: %.2f\n",
7. }; data.floatValue);
8. int main() { 16. // Assign a string to the union
9. // Declare a variable of the 17. strcpy(data.stringValue,
union "Hello, Union!");
10. union MyUnion data; 18. printf("String Value: %s\n",
data.stringValue);
19. return 0;
6
20. }
Size of Union
7
Difference between C Union and C Structure
Feature C Union C Structure
Shares memory space among all Each member has its memory
Memory Allocation
members. space.
Shares memory, using the largest Requires memory for each
Memory Usage
member's size. member simultaneously.
Members share the same memory Members are accessed
Accessing Members
space. individually.
Size is the size of the largest Size is the sum of sizes of its
Size Calculation
member. members.
No wastage as it uses the size of Can lead to memory wastage for
Memory Wastage
the largest member. small types.