union UnionName {
data_type member1;
data_type member2;
data_type member3;
};C++ Unions: Shared Memory Storage and Practical Examples
Direct Answer & Core Concept
C++ provides several user-defined data types that help organize information. Structures (struct) group multiple data members together, while unions (union) allow multiple members to share the same memory location.
Unions are useful when a program needs to store one value from several possible data types at a time.
For example, an application might need to store:
An integer value.
A floating-point value.
A character.
A Boolean value.
Instead of allocating separate storage for every member, a union provides shared storage for its members.
Detailed Explanation & Mechanics
1. What Is a Union in C++?
A union is a user-defined data type in C++ in which all non-static data members share the same memory location.
Unlike a structure, where each member has its own storage, union members overlap in memory.
This means that a union is generally used to hold one active member at a time.
Syntax of a Union
Here:
unionis the keyword used to define a union.UnionNameis the name of the union.member1,member2, andmember3are its data members.The semicolon after the closing brace is required.
Example: Declare a Union
#include <iostream>
using namespace std;
union Data {
int number;
float decimal;
char letter;
};
int main() {
return 0;
}The Data union contains three members:
| Member | Data type | Purpose |
|---|---|---|
number | int | Stores an integer |
decimal | float | Stores a decimal value |
letter | char | Stores a character |
All three members share the same storage.
2. How Does a Union Work in C++?
The main feature of a union is shared memory.
Consider this union:
union Data {
int number;
float decimal;
char letter;
};The compiler allocates enough storage to accommodate its largest member, subject to the type's alignment requirements.
For example, if an implementation uses:
intrequiring 4 bytes,floatrequiring 4 bytes,charrequiring 1 byte,
the union will typically require 4 bytes, although its exact size depends on the implementation and alignment.
<AsyncImage query="C++ union shared memory educational diagram overlapping int float char members same memory block labeled union memory layout simple programming infographic" aspectRatio="16:9" width="100%" maxHeight={220}/>
Important: The members do not have separate independent values. Writing to one member changes the shared storage and generally ends the lifetime of the previously active member.
3. Declaring and Creating Union Variables
After defining a union, you can create variables using its name.
Syntax
UnionName variableName;Example:
union Data {
int number;
float decimal;
char letter;
};
int main() {
Data value;
return 0;
}Here, value is a union object.
You can also create multiple union variables:
Data first;
Data second;
Data third;Each union object has its own shared storage.
4. Accessing Union Members
The dot (.) operator is used to access union members through an object.
Example: Store and Display an Integer
#include <iostream>
using namespace std;
union Data {
int number;
float decimal;
char letter;
};
int main() {
Data value;
value.number = 100;
cout << "Number: " << value.number;
return 0;
}Output:
Number: 100The program stores an integer in the union and reads that same active member.
5. Understanding Shared Memory With an Example
When you assign a value to one union member, that member becomes active.
Consider this example:
#include <iostream>
using namespace std;
union Data {
int number;
float decimal;
char letter;
};
int main() {
Data value;
value.number = 100;
cout << "Integer: " << value.number << endl;
value.decimal = 25.5f;
cout << "Float: " << value.decimal << endl;
return 0;
}Output:
Integer: 100
Float: 25.5Explanation:
value.number = 100activates the integer member.The program reads and displays the integer.
value.decimal = 25.5factivates the floating-point member.The previous integer member is no longer the active member.
The program reads and displays the floating-point value.
The example does not read the inactive integer member after assigning the float.
Important: Do not assume that assigning one union member allows you to read another member as though it still contains its original value. Reading an inactive member is generally not permitted, apart from specific language rules such as inspecting the common initial sequence of standard-layout struct members in an appropriate union.
6. Initializing a Union in C++
You can initialize a union when declaring its variable.
Example 1: Initialize the First Member
#include <iostream>
using namespace std;
union Data {
int number;
float decimal;
char letter;
};
int main() {
Data value = {100};
cout << value.number;
return 0;
}Output:
100Traditional aggregate initialization without a designated member initializes the first member.
Example 2: Initialize a Specific Member Using a Designated Initializer
C++20 supports designated initializers for aggregates.
#include <iostream>
using namespace std;
union Data {
int number;
float decimal;
char letter;
};
int main() {
Data value = {.decimal = 25.5f};
cout << value.decimal;
return 0;
}Output:
25.5The designated initializer identifies which member should be initialized.
7. Updating Union Members
You can change the active member by assigning a value to another member.
Example
#include <iostream>
using namespace std;
union Data {
int number;
float decimal;
char letter;
};
int main() {
Data value;
value.letter = 'A';
cout << "Character: " << value.letter << endl;
value.number = 500;
cout << "Integer: " << value.number << endl;
value.decimal = 12.5f;
cout << "Float: " << value.decimal << endl;
return 0;
}Output:
Character: A
Integer: 500
Float: 12.5Each assignment activates a different member. Only the currently active member is read.
8. Finding the Size of a Union
The sizeof operator returns the size of a union object in bytes.
The size is sufficient to hold its largest member, taking alignment and implementation requirements into account.
Example
#include <iostream>
using namespace std;
union Data {
int number;
double decimal;
char letter;
};
int main() {
cout << "Size of int: " << sizeof(int) << endl;
cout << "Size of double: " << sizeof(double) << endl;
cout << "Size of char: " << sizeof(char) << endl;
cout << "Size of union: " << sizeof(Data) << endl;
return 0;
}Example output on a common platform:
Size of int: 4
Size of double: 8
Size of char: 1
Size of union: 8The exact output depends on the platform and compiler.
The union size is not necessarily the simple sum of its member sizes. It is generally at least as large as its largest member and must also satisfy alignment requirements.
9. Array of Unions in C++
You can create an array of union objects just as you can create an array of structures.
Example
#include <iostream>
using namespace std;
union Data {
int number;
float decimal;
};
int main() {
Data values[3];
values[0].number = 10;
values[1].decimal = 20.5f;
values[2].number = 30;
cout << values[0].number << endl;
cout << values[1].decimal << endl;
cout << values[2].number << endl;
return 0;
}Output:
10
20.5
30Each element in the array is a separate union object with its own shared storage.
10. Pointers to Unions
You can create a pointer that stores the address of a union object.
Use the arrow (->) operator to access members through the pointer.
Example
#include <iostream>
using namespace std;
union Data {
int number;
float decimal;
};
int main() {
Data value;
Data* ptr = &value;
ptr->number = 100;
cout << "Number: " << ptr->number;
return 0;
}Output:
Number: 100Here:
ptrstores the address of the union object.ptr->numberaccesses the integer member.The integer member becomes active when assigned.
The arrow operator is equivalent to dereferencing the pointer and using the dot operator:
(*ptr).number;11. Passing a Union to a Function
Like structures, unions can be passed to functions by value, by reference, or by constant reference.
Example: Pass a Union by Value
#include <iostream>
using namespace std;
union Data {
int number;
float decimal;
};
void display(Data value) {
cout << "Number: " << value.number << endl;
}
int main() {
Data data;
data.number = 100;
display(data);
return 0;
}Output:
Number: 100The function receives a copy of the union object. In this example, the integer member is active in the copied object.
Example: Pass a Union by Reference
#include <iostream>
using namespace std;
union Data {
int number;
float decimal;
};
void update(Data& value) {
value.number = 500;
}
int main() {
Data data;
data.number = 100;
update(data);
cout << data.number;
return 0;
}Output:
500Passing by reference allows the function to update the original union object.
12. Union With a Structure in C++
A union can be used as a member of a structure. This is useful when a record can contain one of several possible value types.
However, the program should also store information identifying which union member is active.
This is commonly called a tagged union or discriminated union.
Example: Structure With a Union Member
#include <iostream>
using namespace std;
struct Value {
int type;
union {
int integerValue;
float floatValue;
char characterValue;
} data;
};
int main() {
Value value;
value.type = 1;
value.data.integerValue = 100;
if (value.type == 1) {
cout << "Integer: " << value.data.integerValue;
}
return 0;
}Output:
Integer: 100Explanation:
typeidentifies the active value type.datastores the selected value in shared memory.The program checks
typebefore reading the corresponding union member.
The programmer must keep the tag and active union member consistent.
For many applications, std::variant is a safer alternative because it tracks the currently held type automatically.
13. Difference Between Structure and Union in C++
Structures and unions are both user-defined data types, but their memory organization is different.
| Feature | Structure (struct) | Union (union) |
|---|---|---|
| Memory allocation | Separate storage for each non-static member | Members share storage |
| Member values | All members can hold independent values | Normally one active member at a time |
| Size | Includes storage for all members and padding | Sufficient for the largest member and alignment |
| Access | Dot or arrow operator | Dot or arrow operator |
| Use case | Grouping related data | Alternative values sharing storage |
| Member initialization | Supports multiple members | Initializes an active member |
Example: Structure
struct Data {
int number;
float decimal;
char letter;
};All three members can hold independent values at the same time.
Example: Union
union Data {
int number;
float decimal;
char letter;
};The members share storage, so the union is generally used for one active value at a time.
14. Union vs std::variant in Modern C++
C++17 introduced std::variant, which provides a type-safe way to store one value from a list of alternative types.
Unlike a raw union, std::variant tracks which alternative is currently active and manages the lifetime of its contained value.
Example: Using std::variant
#include <iostream>
#include <variant>
using namespace std;
int main() {
variant<int, float, string> value;
value = 100;
cout << get<int>(value) << endl;
value = 25.5f;
cout << get<float>(value) << endl;
value = string("Hello C++");
cout << get<string>(value) << endl;
return 0;
}Output:
100
25.5
Hello C++std::variant is often a better choice when you need a value that can hold one of several different types safely.
| Feature | Union | std::variant |
|---|---|---|
| Introduced | Available in C++ | C++17 |
| Shared storage | Yes | Uses storage for its alternatives |
| Tracks active type | Not automatically | Yes |
| Type safety | Requires careful management | Type-safe access |
| Complex member types | Requires careful lifetime management | Supports suitable non-trivial types |
| Typical use | Low-level storage and specialized layouts | Type-safe alternative values |
15. Real-World Applications of Unions in C++
Unions can be useful in applications where memory layout and alternative data representations matter.
Embedded Systems
Embedded applications may use unions to represent different interpretations of data while working with constrained memory.
Hardware and Device Programming
Low-level code may use unions when interacting with hardware representations, provided the implementation and hardware requirements are properly understood.
Network Protocols
A data field may represent different types of information depending on a message type or protocol tag.
Compilers and Interpreters
A value representation may need to store one of several possible data types.
Memory-Constrained Applications
Unions can reduce storage requirements when only one of several alternative values needs to be active at a time.
Note: Unions do not automatically make a program faster. Choose them when their shared-storage behavior is genuinely useful.
16. Common Mistakes When Using Unions
Mistake 1: Reading an Inactive Member
Incorrect:
union Data {
int number;
float decimal;
};
int main() {
Data value;
value.number = 100;
cout << value.decimal; // Generally not valid
}The integer member is active. Reading the floating-point member this way is not generally permitted by the C++ object-lifetime rules.
Read the active member instead.
Mistake 2: Assuming All Members Have Separate Values
union Data {
int number;
float decimal;
};You should not treat number and decimal as independent storage locations. They overlap.
Mistake 3: Forgetting to Track the Active Member
When a union is used inside a larger structure, the program should keep track of which member is active.
Without that information, code may accidentally read the wrong member.
Mistake 4: Ignoring Member Lifetime Rules
Unions containing types with non-trivial constructors or destructors require careful lifetime management.
For complex alternative types, consider std::variant instead.
Mistake 5: Assuming the Union Size Is the Sum of Its Members
A union does not normally allocate separate storage for every member. Its size is based on its largest member and alignment requirements, not the sum of all member sizes.
17. Best Practices for Using Unions
Use unions only when shared storage is genuinely required.
Keep track of the currently active member.
Never read an inactive member unless a specific C++ language rule permits it.
Use
std::variantwhen you need type-safe alternative values.Be careful with unions containing complex types such as
std::string.Understand object lifetime and construction rules before using non-trivial union members.
Avoid relying on platform-specific memory layouts unless the application requires them.
Test low-level union code with the intended compiler and target platform.
Document which member is active and how that state is maintained.
Prefer simpler structures or standard library types when shared storage is unnecessary.
18. Frequently Asked Questions (FAQs)
1. What is a union in C++?
A union is a user-defined data type in which all non-static data members share the same memory location.
2. Which keyword is used to create a union?
The union keyword is used to declare a union in C++.
3. How is a union different from a structure?
A structure provides separate storage for its non-static data members, while union members share storage.
4. Can a union contain different data types?
Yes. A union can contain members with different data types, such as int, float, char, and other suitable types.
5. Can all union members store independent values at the same time?
No. A union normally has one active member at a time because its members share the same storage.
6. How do you access union members?
Use the dot (.) operator with a union object or the arrow (->) operator with a pointer.
7. How do you find the size of a union?
Use the sizeof operator:
sizeof(Data);The result depends on the largest member and the alignment requirements.
8. Can we create an array of unions?
Yes. You can declare an array of union objects:
Data values[5];Each element has its own union storage.
9. Can a union contain a structure?
Yes. A union can contain a structure as one of its members, subject to the normal member lifetime rules.
10. Can we pass a union to a function?
Yes. You can pass a union by value, by reference, or by constant reference.
11. Can a union contain a string in C++?
Yes, but a std::string is a non-trivial type. Managing its construction, destruction, and active-member lifetime inside a union requires care. std::variant is often a safer option.
12. What is std::variant?
std::variant is a C++17 standard library type that stores one value from several alternative types and tracks which type is currently active.
Runnable Code Example: C++ Unions
C++20 / C++23#include <iostream>
#include <variant>
#include <string>
// Type-safe Modern C++17 Variant
using ConfigValue = std::variant<int, double, std::string>;
int main() {
ConfigValue setting = 404; // Holds int
std::cout << "Integer value: " << std::get<int>(setting) << "
";
setting = std::string("https://operatetools.com/api"); // Holds string
std::cout << "String value: " << std::get<std::string>(setting) << "
";
// Pattern matching with std::visit
std::visit([](const auto& val) {
std::cout << "Visited active value: " << val << "
";
}, setting);
return 0;
}