codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
⚡

C++ Programming

32 / 87 topics
28Structures (struct)29Structure and Function30Pointers to Structure31Enumerations (enum)32Unions
Tutorials/C++ Programming/Unions
⚡C++ Programming

Unions

Updated 2026-05-12
30 min read

Unions

In this tutorial, we will explore the concept of unions in C++. Unions are a powerful feature that allows you to store different data types in the same memory location. This can be particularly useful when you need to save memory or when dealing with hardware interfaces where multiple data types might occupy the same physical memory space.

Introduction

Unions provide an alternative to structures (struct) by allowing you to define a variable that can hold different data types at different times, but only one at a time. This sharing of memory is what makes unions unique and useful in certain scenarios.

Understanding unions is crucial for optimizing memory usage in C++ programs, especially when working with limited resources or interfacing with hardware. In this tutorial, we will cover the syntax of unions, how they differ from structures, their use cases, and some common pitfalls to avoid.

Union Syntax

A union is defined using the union keyword, similar to a structure. Here's the basic syntax:

C++
1union UnionName {
2 dataType1 member1;
3 dataType2 member2;
4 // ...
5};

Example 1: Basic Union Definition

Let's define a simple union that can hold either an integer or a float.

basic_union.cpp
1union Number {
2 int intValue;
3 float floatValue;
4};
5
6int main() {
7 Number num;
8 num.intValue = 42;
9 std::cout << "Integer value: " << num.intValue << std::endl; // Output: Integer value: 42
10
11 num.floatValue = 3.14;
12 std::cout << "Float value: " << num.floatValue << std::endl; // Output: Float value: 3.14
13
14 return 0;
15}
Output
Integer value: 42
Float value: 3.14

Explanation

  • The union Number can hold either an int or a float.
  • When you assign a value to one member, the memory occupied by that union is overwritten.
  • Therefore, after assigning a float value, the integer value is lost.

Memory Sharing in Unions

The key feature of unions is their ability to share memory. This means that all members of a union occupy the same memory location, and only one can be used at a time.

Example 2: Understanding Memory Sharing

Let's examine how memory sharing works with a slightly more complex example.

memory_sharing.cpp
1union Data {
2 int i;
3 float f;
4 char str[20];
5};
6
7int main() {
8 Data data;
9
10 data.i = 10;
11 std::cout << "Integer: " << data.i << std::endl; // Output: Integer: 10
12
13 data.f = 3.14;
14 std::cout << "Float: " << data.f << std::endl; // Output: Float: 3.14
15
16 strcpy(data.str, "Hello");
17 std::cout << "String: " << data.str << std::endl; // Output: String: Hello
18
19 return 0;
20}
Output
Integer: 10
Float: 3.14
String: Hello

Explanation

  • The union Data can hold an integer, a float, or a string.
  • Each assignment to a member overwrites the previous data in the union.
  • This is why the integer and float values are lost when we assign a string.

Union vs Struct

While unions and structures share some similarities, they have distinct differences:

Featurestructunion
Memory AllocationEach member has its own memory allocation.All members share the same memory location.
UsageSuitable for storing multiple related data items together.Suitable for storing one of several possible types in the same memory.
SizeThe size is the sum of the sizes of all members.The size is the size of the largest member.

Example 3: Comparing struct and union

Here's a comparison using both a structure and a union with similar members.

struct_vs_union.cpp
1#include <iostream>
2#include <cstring>
3
4struct Structure {
5 int i;
6 float f;
7 char str[20];
8};
9
10union Union {
11 int i;
12 float f;
13 char str[20];
14};
15
16int main() {
17 std::cout << "Size of struct: " << sizeof(Structure) << " bytes" << std::endl; // Output: Size of struct: 36 bytes
18 std::cout << "Size of union: " << sizeof(Union) << " bytes" << std::endl; // Output: Size of union: 20 bytes
19
20 return 0;
21}
Output
Size of struct: 36 bytes
Size of union: 20 bytes

Explanation

  • The structure Structure allocates separate memory for each member, resulting in a larger size.
  • The union Union shares the same memory location among its members, making it more memory-efficient.

Anonymous Unions

An anonymous union is a union without a name. It allows you to access the members directly without using the union's name as a prefix.

Example 4: Using an Anonymous Union

Here's how you can define and use an anonymous union.

anonymous_union.cpp
1union {
2 int i;
3 float f;
4 char str[20];
5};
6
7int main() {
8 i = 10;
9 std::cout << "Integer: " << i << std::endl; // Output: Integer: 10
10
11 f = 3.14;
12 std::cout << "Float: " << f << std::endl; // Output: Float: 3.14
13
14 strcpy(str, "Hello");
15 std::cout << "String: " << str << std::endl; // Output: String: Hello
16
17 return 0;
18}
Output
Integer: 10
Float: 3.14
String: Hello

Explanation

  • The union is defined without a name, so you can access its members directly.
  • This can be useful in small scopes where clarity and brevity are preferred.

Use Cases for Unions

Unions are particularly useful in the following scenarios:

  1. Memory Optimization: When you need to save memory by sharing storage for different data types.
  2. Hardware Interfaces: When interfacing with hardware where multiple data types might occupy the same physical memory space.
  3. Union of Structures: Combining unions and structures to represent complex data types.

Example 5: Union of Structures

Here's an example of using a union within a structure.

union_of_structures.cpp
1struct Color {
2 int red;
3 int green;
4 int blue;
5};
6
7struct HexColor {
8 char hex[7];
9};
10
11union ColorUnion {
12 Color rgb;
13 HexColor hex;
14};
15
16struct Pixel {
17 int x;
18 int y;
19 ColorUnion color;
20};
21
22int main() {
23 Pixel pixel;
24 pixel.x = 10;
25 pixel.y = 20;
26
27 pixel.color.rgb.red = 255;
28 pixel.color.rgb.green = 0;
29 pixel.color.rgb.blue = 0;
30
31 std::cout << "RGB Color: (" << pixel.color.rgb.red << ", "
32 << pixel.color.rgb.green << ", "
33 << pixel.color.rgb.blue << ")" << std::endl; // Output: RGB Color: (255, 0, 0)
34
35 strcpy(pixel.color.hex.hex, "#FF0000");
36 std::cout << "Hex Color: " << pixel.color.hex.hex << std::endl; // Output: Hex Color: #FF0000
37
38 return 0;
39}
Output
RGB Color: (255, 0, 0)
Hex Color: #FF0000

Explanation

  • The ColorUnion union can hold either an RGB color or a hexadecimal color.
  • This is useful in graphics programming where you might need to represent colors in different formats.

Common Mistakes and Pitfalls

  1. Accessing Multiple Members Simultaneously: Since all members of a union share the same memory, accessing multiple members simultaneously leads to undefined behavior.
  2. Incorrect Memory Management: Unions do not manage memory allocation or deallocation automatically, so you must be careful when using dynamic memory with unions.

Practical Example

Let's create a practical example that demonstrates the use of unions in a real-world scenario. We'll create a program that can store either an integer or a float and perform operations based on the type stored.

practical_union.cpp
1#include <iostream>
2
3union Number {
4 int intValue;
5 float floatValue;
6};
7
8enum Type { INTEGER, FLOAT };
9
10struct Data {
11 Type type;
12 Number num;
13};
14
15void printData(Data data) {
16 if (data.type == INTEGER) {
17 std::cout << "Integer: " << data.num.intValue << std::endl;
18 } else if (data.type == FLOAT) {
19 std::cout << "Float: " << data.num.floatValue << std::endl;
20 }
21}
22
23int main() {
24 Data data1;
25 data1.type = INTEGER;
26 data1.num.intValue = 42;
27
28 printData(data1);
29
30 Data data2;
31 data2.type = FLOAT;
32 data2.num.floatValue = 3.14;
33
34 printData(data2);
35
36 return 0;
37}
Output
Integer: 42
Float: 3.14

Explanation

  • The Number union can store either an integer or a float.
  • The Type enumeration is used to keep track of the current type stored in the union.
  • The Data structure combines the union and the type information.
  • The printData function prints the value based on the type.

Summary

Key PointsDescription
DefinitionUnions allow storing different data types in the same memory location.
Memory SharingAll members share the same memory, only one can be used at a time.
SizeThe size of a union is determined by its largest member.
Use CasesUseful for memory optimization and hardware interfaces.
Anonymous UnionsUnions without names allow direct access to their members.
Common PitfallsAccessing multiple members simultaneously leads to undefined behavior.

What's Next?

In the next tutorial, we will explore pointers in C++. Pointers are fundamental for understanding memory management and dynamic data structures. After mastering unions, pointers will provide you with even more control over memory and enable you to write more efficient and powerful programs.

Stay tuned!


PreviousEnumerations (enum)Next Pointers

Recommended Gear

Enumerations (enum)Pointers