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; } |
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:
- Pre-defined DataTypes
- Derived Data Types
- User-defined DataTypes
In this article, the User-Defined DataType is explained:
Contact Us