Nearby lessons
62 of 72C - Unions
A union in C is similar to a structure, but all its members share the same memory. This lesson explains how to define a union, create a union variable, access its members, and understand the difference between a structure and a union.
1. What Is a Union?
A union is a user-defined data type in C. It can contain members of different data types, such as int, float, and char.
The main difference is that all union members share the same memory area.
In simple words: A structure gives each member its own space, while a union allows all members to share one space.
2. Declare and Access a Union
After defining a union, create a variable using the union keyword. Use the dot operator (.) to access its members.
3. How Does a Union Share Memory?
All members of a union start at the same memory location. When you store a new value in a different member, the previously stored value may no longer be available in its original form.
In the following example, we first store an integer and then store a float. After writing to price, we read only the active member, price.
4. Size of a Union
The size of a union is large enough to hold its largest member, with any extra space required for memory alignment. The exact size can depend on the compiler and system.
6. When Should We Use a Union?
- Use a structure when all values, such as a student's name, roll number, and marks, need to be stored together.
- Use a union when a value needs to represent one of several different data types at a time.
- A union can help reduce memory usage when only one member needs to be stored at a time.
Common Mistakes
- Do not assume that all union members can hold independent values at the same time.
- Use the correct format specifier when displaying a member.
- After assigning a new member, read the member you most recently stored rather than relying on the old value.
- Do not assume the union size is always exactly the sum of its members or always a particular number of bytes.
- The union keyword is used to define a union.
- All members of a union share the same memory area.
- Use the dot (.) operator to access a union member.
- A union can store different types of values, but its members share memory.
- The size of a union is enough to hold its largest member, including any required alignment.
- Use a structure when you need to store all members separately.