| by Arround The Web | No comments

C++ Union Examples

A union is a special class type in C++ that enables the storage of different data types in a shared memory location. Unlike structures, where each part usually gets its memory, unions let the different pieces of data use the same memory location. This characteristic makes unions particularly useful when memory efficiency is a priority, and only one of the members needs to be accessed at a time. In this article, we will delve into the concept of unions in C++ and explore multiple examples that demonstrate their utility in various scenarios.

Syntax:

A union is a type that is defined by the user, enabling the storage of diverse data types within a shared memory location. Using a union follows a syntax that is identical to a struct.

The fundamental syntax is as follows:

union UnionName {

  // Member declarations

  DataType1 member1;

  DataType2 member2;

  // ...

};

Here, “UnionName” serves as the identifier for the union which provides a unique name to reference this specific user-defined type. The union members’ data types are denoted as “DataType1”, “DataType2”, and so forth. These data types signify the varied types of information that can be stored within the union. Each member within the union, designated by names such as “member1”, “member2”, etc., represents a distinct piece of data.

We now understand the basic syntax. Let’s now use a few instances to better understand this.

Example 1: Basic Union Usage

The first example illustrates the basic utilization of unions in C++, showcasing how they enable the sharing of memory space among different data types within a single structure.

Here is an example:

#include <iostream>

using namespace std;

union ArrayUnion {

  int intArray[5];

  float floatArray[5];

};

int main() {

  ArrayUnion arrayUnion;

  for (int i = 0; i < 5; ++i) {

    arrayUnion.intArray[i] = i * 2;

  }

  cout << "Int Array:";
 
  for (int i = 0; i < 5; ++i) {

    cout << " " << arrayUnion.intArray[i];

  }

  cout << endl;

  for (int i = 0; i < 5; ++i) {

    arrayUnion.floatArray[i] = i * 1.5f;

  }

  cout << "Float Array:";

  for (int i = 0; i < 5; ++i) {

    cout << " " << arrayUnion.floatArray[i];

  }

  cout << endl;

  return 0;

}

In this C++ code snippet, we utilize a union named “MyUnion” that incorporates three different data members: an integer (intValue), a floating-point number (floatValue), and a character (charValue). Only one of these members may be active at any given point due to a union’s ability to share a memory space.

Within the “main” function, we declare an instance of the union which is “myUnion”. First, we set the integer member’s value to 42 and use “cout” to print it. Subsequently, we assign the floating-point value of 3.14 to the “floatValue” member and print it. Lastly, we assign the character “A” to the “charValue” member and print it. It’s essential to remember that since all union members share the same memory location, altering one member may have an impact on the values of other members. The code concludes by returning 0 which signifies a successful execution.

Example 2: Union with Struct

A struct is a type of data in C++ that the users can create to combine the variables of various types under one unified name. Combining a union with a struct can be useful when we want to create a data structure that can hold different types of data, and each type is associated with a specific field. This pairing allows for the development of complex data structures featuring diverse representations.

Here’s an example of using a union within a struct in C++:

#include <iostream>

using namespace std;

struct Point {

  int s1;

  int s2;

};

union Shape {

  int sides;

  float radius;

  Point center;

};

int main() {

  Shape shape;

  shape.sides = 5;
  cout << "Sides: " << shape.sides << endl;

  shape.radius = 6.0f;
  cout << "Radius: " << shape.radius << endl;

  shape.center = {10, 20};
  cout << "Center: (" << shape.center.s1 << ", " << shape.center.s2 << ")" << endl;

  return 0;

}

In this code, we define a C++ program that uses a union and a struct to represent different aspects of a geometric shape. First, we declare a “Point” structure which consists of two integer members, “s1” and “s2”, that represent the coordinates of a point in a 2D space. Then, we define a “union” named “Shape” which consists of three members: a “sides” integer, a “radius” floating-point, and a “Point” struct named “center”. Moving on to the “main” function, we instantiate a “Shape” object named “shape”. We then demonstrate the versatility of the union by assigning values to its different members. Initially, we set the number of sides to 5 and print the result. Next, we assign a radius of 6.0 to the shape and output the radius. Finally, we assign a center point with coordinates (10, 20) to the shape and print the center’s coordinates.

Example 3: Union with Enum

In C++, enumerations, commonly referred to as enums, serve the purpose of defining a collection of named integral constants. Combining enums with unions can be useful in scenarios where we want to represent a variable that can take on different types, each associated with a specific enum value.

Here’s an example:

#include <iostream>

using namespace std;

enum DataType {

  INTEGER,

  FLOAT,

  CHAR

};

union DataValue {

  int intValue;

  float floatValue;

  char charValue;

};

struct Data {
 
  DataType type;

  DataValue value;

};

int main()

{

  Data data1, data2, data3;

  data1.type = INTEGER;
  data1.value.intValue = 42;

  data2.type = FLOAT;
  data2.value.floatValue = 3.14f;

  data3.type = CHAR;
  data3.value.charValue = 'A';

  cout << "Data 1: " << data1.value.intValue << endl;
  cout << "Data 2: " << data2.value.floatValue << endl;
  cout << "Data 3: " << data3.value.charValue << endl;

  return 0;

}

For this example, we have a program that utilizes enums, unions, and structs to create a flexible data structure that is capable of holding different types of values. The “DataType” enum is defined to represent three fundamental data types: INTEGER, FLOAT, and CHAR. The enum enhances the code readability and maintainability by offering a set of named integral constants.

Then, we make a union called “DataValue” with three members: “charValue” of type char, “floatValue” of type float, and “intValue” of type int. With a union, these members share a common memory location which allows the union to interchangeably accommodate the values of distinct types. The “Data” struct is then created which consists of two members: a “DataType” enumerator named “type” and a “DataValue” union named “value”. This struct allows us to associate a data type with its corresponding value, providing a structured representation.

In the “main” function, we instantiate three instances of the “Data” struct: “data1”, “data2”, and “data3”. We assign the values to these instances by specifying the data type and setting the appropriate value within the union. For example, “data1” is assigned with an INTEGER type with a value of 42. Finally, we use the “cout” statements to print the values that are stored in each “Data” instance. The program outputs the integer value of “data1”, the floating-point value of “data2”, and the character value of “data3”.

This example illustrates how combining the enums, unions, and structs can be employed to create a versatile and type-safe data representation in C++.

Conclusion

C++ unions provide a powerful and flexible mechanism for managing the diverse data types within a single memory space. The instances that are illustrated in this article highlight the adaptability and effectiveness of unions in addressing a range of scenarios. From the fundamental uses that demonstrate the interchangeability of data types to a more complex applications involving structures and enums, these examples underscore the efficiency and adaptability that unions bring to C++ programming.

Share Button

Source: linuxhint.com

Leave a Reply