C Unions
1. What is a Union?
-
A union is similar to a structure (
struct) in C, but all members share the same memory location. -
Only one member can store a value at a time.
-
Useful for memory-efficient programs when you need alternative data types in the same location.
Syntax:
2. Example: Basic Union
Output:
Only one member’s value is valid at a time.
3. Size of a Union
-
The size of a union is equal to the size of its largest member.
Output:
-
stris the largest member → union size = 20 bytes.
4. Union with Struct Example
Output:
5. Key Points About Unions
-
All members share the same memory location.
-
Only one member can hold a value at a time.
-
Memory size = size of largest member.
-
Useful for memory-efficient storage and type alternatives.
-
Access union members with dot
.(normal) or arrow->(pointer). -
Often used in embedded systems, protocol implementations, and type conversion.
