Understanding Unions in C++ with Example.

In C++, a union is a special data type that allows the storage of different data types in the same memory location. Unions provide a way to save memory by enabling variables to share memory space, which can be useful in certain programming scenarios. 


In this article we will explore the concept of unions in C++, covering their definition, and usage with examples, and highlighting the key differences between unions and structures.


What is a Union in C++?

A union in C++ is a user-defined data type that enables variables of different data types to share the same memory space. Unlike structures, where each member has its own memory allocation, union members overlap in memory. The size of a union is determined by the largest member within it.


Syntax:

union UnionName {
    // Member declarations
    DataType1 member1;
    DataType2 member2;
    // ...
};


Usage of Union in C++.

Unions are primarily used when you want to store different types of data in the same memory space, but only one member of the union can be active at any given time. This allows memory efficiency and can be handy in situations where you need to conserve memory or represent variant data.


Example Union Program in C++:

//C++ Program to show working on union
#include <iostream>
using namespace std;

//declare union
union NumericValue {
    int value1;
    float value2;
};

int main() {
    NumericValue value;
    value.value1 = 42;
    
    cout << "Integer Value: " << value.value1 << endl;
    
    value.value2 = 3.14;
    
    cout << "Float Value: " << value.value2 << endl;
    cout << "Integer Value after assigning float: " << value.value1 << endl;
    
    return 0;
}
Output:
Integer Value: 42
Float Value: 3.14
Integer Value after assigning float: 1078523331

In this example code, we have a union named NumericValue that contains two members: value1 of type int and value2 of type float. We will use this union to store either an integer or a float value in the same memory space.

In the main() function, we create an instance of the union named value. Initially, we assign the value 42 to value1 and print it as the "Integer Value." Since only the value1 member is active at this point, accessing it yields the expected result.

Next, we assign the value 3.14 to value2 and print it as the "Float Value." However, note that after assigning a value to value2, the value1 member is no longer valid, and accessing it results in undefined behavior.

To demonstrate this, we print the "Integer Value after assigning float" which may give an unexpected output due to the memory overlap. The output may vary depending on the system, compiler, and memory representation.
Note: Only one member can be active at any given time, sharing the memory space allocated for the union. Accessing a member other than the one currently active may result in undefined behavior. (alert-passed)

How it is different from structure?

The key difference between union and structure:

  • In a structure, each member has its own memory allocation, and all members can be accessed independently. In contrast, a union allows different members to share the same memory space, but only one member can be active at any given time.
  • Unions are most commonly used to conserve memory or represent variant data, whereas structures are used to group related data elements into a single entity.
  • Accessing a member of a union that is not currently active can lead to unpredictable results or undefined behavior. It is the programmer's responsibility to keep track of the active member and ensure correct usage.

By understanding unions and their characteristics, you can leverage them effectively in your C++ programs to optimize memory usage and handle variant data requirements efficiently.

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS