Unions

The union, like Structures, is a user-defined data type. They handle memory more effectively than structures. The memory location is shared by all union members.

The union is a data type that allows diverse types of data to be stored in the same memory regions. One advantage of employing a union over a structure is that it allows for more efficient memory reuse because only one of its members can be accessed at a time. A union is declared and used in the same way as a structure is. The only variation is how memory is assigned to their members.

Creating a Union element

To define the union, we utilise the union term.

The syntax for defining a union is as follows:

union union_name
{
    //union_elements
} union_variable;

Here’s one example of how a union is defined and used in main as a user-defined data type.

#include <iostream>
using namespace std;
 
union money
{
    /* data */
    int rice;
    char car;
    float pounds;
};
 
int main()
{
    union money m1;
}

Initialising and accessing union elements

Union elements are initialised one at a time, unlike structs, which are initialised in a single step.

Furthermore, only one union element can be accessed at a time. When one union element is changed, the value contained in the other union elements is affected.

#include <iostream>
using namespace std;
 
union money
{
    /* data */
    int rice;
    char car;
    float pounds;
};
 
int main()
{
    union money m1;
    m1.rice = 34;
    cout << m1.rice;
    return 0;
}

Output:

34
Shubhajna Rai
Shubhajna Rai

A Civil Engineering Graduate interested to share valuable information with the aspirants.

Leave a Reply

Your email address will not be published. Required fields are marked *

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.

    StudentProjects.in