C++. Unions. The keyword ‘union’. Examples of declaring and using unions




Unions. The keyword ‘union’. Examples of declaring and using unions


Contents


Search other websites:

1. What is the union in the language C++? What are the unions used for?

Unions – a grouping of variables that share the same memory space. Depending on the interpretation, one or more union variables are accessed. All variables that are included in the union begin with one boundary.

Union allows you to present in a compact form data that can change. The same data can be represented in different ways by using unions.

Just like structures, unions require declaration of a type (template) and declaration of a variable of this type.

2. What does the general form of the declaration of the union type (template) look like? The keyword union

A union declaration begins with the keyword ‘union’.

union union_type_name
{
    type variable1;
    type variable2;
    ...
    type variableN;
};

where

  • union_type_name – the name of the newly created type;
  • variable1, variable2, variableN – variables that are the union fields. These variables can be of different types;
  • type – the type of the variable that is the union field.

The type of the variable can be:

3. What is the length of the union? How is the union length calculated?

The length of the union is the size of the memory in bytes, which is allocated for one variable of this union type. The union length is calculated as the maximum of all lengths (byte sizes) of the individual template fields. It should be recalled that one field is the declaration of one variable in the union.

4. How do I declare a union type and a variable of this type? Example

Suppose we are given a union type that contains floating-point type variables

// type declaration "union Floats"
union Floats
{
    float f; // 4 bytes are considered
    double d; // 8 bytes are considered
};

The union type Floats contains 2 variables with the names f and d. The variable f is of type float, the variable d is of type double. For a variable f of type float, 4 bytes are considered. For a variable d of double type, 8 bytes are taken into account, since the compiler allocates 8 bytes for this type.

To use the Floats union in another code (method, event handler, etc.), you need to declare a variable of type Floats as shown below

Floats Fl;
int d;
Fl.f = 20.5; // Fl.d undefined
Fl.d = -100.35; // now Fl.f undefined

d = sizeof(Fl); // d = 8

Since the allocation of variables in the memory conventionally starts with one address, for Fl variable is allocated 8 bytes of memory. This is due to the fact that a variable of type double requires more memory for its representation than a variable of type float.

Figure 1 shows the location (interpretation) of the variables f, d from the Floats union.

C++ union fields representation

Figure 1. Representation of the variables f, d in union Floats

5. How do I access the union fields?

Access to union fields is the same as for the structure:

  • using the character ‘ . ‘;
  • with the sequence of the characters ‘->’ in the case when the variable-pointer to the union is declared.





6. Example of declaring and using a pointer (*) to the union

The work of unions with unmanaged (*) pointers is exactly the same as the work of structures with unmanaged pointers.

In the following example, an unmanaged pointer to an Ints union is declared

// pointer to the union
Ints *p; // unmanaged pointer

// allocate memory for union
p = new Ints;

// access to fields using the pointer
pI->a = 200;
pI->b = 3400;

7. How do I declare nested unions (structures, classes) in a union template? Example

A union template can include fields, which are structures, unions, and classes.

The example below declares a union template named Types, containing two nested Floats and Ints unions, an ArrayOfChars structure, and a MyPoint class.

The declaration of structures and unions has the following form

// union of integer types
union Ints
{
    unsigned short int a;
    unsigned int b;
    unsigned long int c;
};

// structure containing 2 lines
struct ArrayOfChars
{
    char A[10];
    char B[8];
};

// declaration of union type "Floats"
union Floats
{
    float f; // 4 bytes are considered
    double d; // 8 bytes are considered
};

The declaration of a class template is as follows:

// class is declared in a separate module, for example, MyPoint.h
#pragma once
class MyPoint
{
    public:
        int x;
        int y;

        // class methods
        int GetX(void) { return x; }
        int GetY(void) { return y; }
        void SetXY(int nx, int ny) { x = nx; y = ny; }
};

A declaration of type Types union with nested complex types of Ints, Floats, ArrayOfChars, MyPoint.

// include the module with the declared MyPoint class
#include "MyPoint.h"

...

// type declaration "union Types"
union Types
{
    Floats Fl; // union
    Ints I;   // union
    ArrayOfChars A; // structure
    MyPoint MP;   // class
};

Using the union ‘Types’ in some program code:

// declare a variable of type "union Types"
Types T;

// change the values of the fields of the variable T
T.Fl.f = (float)20.35; // union Floats
T.I.b = 230; // union Ints
T.A.A[2] = 'A'; // structure ArrayOfChars
T.MP.SetXY(3,8); // class MyPoint
int d;
d = T.MP.GetX(); // d = 3

8. How to declare an array of unions? Example
// Example of declaring and using an array of unions
Floats F[5]; // An array of 5 unions of the Floats type is declared

// filling the fields values
for (int i=0; i<5; i++)
{
    F[i].d = i*0.2 + i*i;
}

9. What are the specific features of using the sizeof() operation for unions and structures?

In C++ programs, you must use the sizeof operation to determine the size of a variable of type “structure” or “union”. The definition of the size “manually” is erroneous because:

  • the sizes of some built-in types (for example, type int) can be different for different computers. For example, on some platforms, for an int type, 2 bytes will be allocated, for others 4 bytes;
  • the compiler does the so-called “memory alignment” on the border of a word (2 bytes) or paragraph (16 bytes).For example, if the compiler does alignment at the paragraph boundary, then the structure (union) of the type ArraysOfChars:
// structure containing 2 strings
struct ArrayOfChars
{
    char A[10];
    char B[8];
};

can occupy 24 bytes in memory. Since the array A is allocated 16 bytes instead of 10 bytes. The compiler additionally allocates 6 bytes to implement alignment at the paragraph boundary.

Thus, using the sizeof() operation to determine the type of structure or union guarantees the portability of the program code.


Related topics