Union

Like Structures , Union a user-defined data type. In union, all members share the same memory location. For example in the following C program, both x and y share the same location. If we change x, we can see the changes being reflected in y.

Syntax

Union_Name 
{
// Declaration of data members
}; union_variables;

Example:

The below example demonstrates the use of union in C++.

CPP




#include <iostream>
using namespace std;
  
// Declaration of union is same as the structures
union test {
    int x, y;
};
  
int main()
{
    // A union variable t
    union test t;
  
    // t.y also gets value 2
    t.x = 2;
  
    cout << "After making x = 2:" << endl
         << "x = " << t.x << ", y = " << t.y << endl;
  
    // t.x is also updated to 10
    t.y = 10;
  
    cout << "After making Y = 10:" << endl
         << "x = " << t.x << ", y = " << t.y << endl;
  
    return 0;
}


Output

After making x = 2:
x = 2, y = 2
After making Y = 10:
x = 10, y = 10

Explanation: The above program demonstrates the use of unions. Union named “test” with integer members x and y is defined, here x and y shares the same memory space. In the main function value of x is set to 2 and then printed. Later, it updates y to 10 and the value of x is also updated to 10, this shows the shared memory characteristic of unions.

User Defined Data Types in C++

Data types are means to identify the type of data and associated operations of handling it. improve. In C++ datatypes are used to declare the variable. There are three types of data types:

  1. Pre-defined DataTypes
  2. Derived Data Types
  3. User-defined DataTypes

In this article, the User-Defined DataType is explained:

Similar Reads

User-Defined DataTypes

The data types that are defined by the user are called the derived datatype or user-defined derived data type. These types include:...

1. Class

A Class is the building block of C++ that leads to Object-Oriented programming is a Class. It is a user-defined data type, which holds its own data members and member functions, which can be accessed and used by creating an instance of that class. A class is like a blueprint for an object....

2. Structure

...

3. Union

A Structure is a user-defined data type in C/C++. A structure creates a data type that can be used to group items of possibly different types into a single type....

4. Enumeration

...

5. Typedef

Like Structures , Union a user-defined data type. In union, all members share the same memory location. For example in the following C program, both x and y share the same location. If we change x, we can see the changes being reflected in y....

Conclusion

...

Contact Us