union in C++ with examples

In this page we will discuss these two topics


C++ union

unions are the same as the structure type, means a collection of similar and different data types.

But where the memory location of the members of the structure is different for each member, the union reserves same location in the memory to all its data member, due to which they affect each other,

you can understand this in such a way that, when you enter the second value after entering the first value, the second value erase the first value, in this way only the value entered in the last is stored, and when we print these values, in the place of erasing values, we get garbage values, that is only the value entered in last in print.

we will discuss here

In the diagram below, you can see that the union reserves the same location in the memory for its data members, that is, the memory address of all the members is the same.

due to union members being reserved in the same memory address, these store values affect each other, due to which the user gets garbage values.

Declaration of union-members in C++

The declaration of structure and union is the same. You can understand it with the syntax given below-

union union-name {
  data member1;
  data member2;
  data member n;
};

Where a union is an identifier, which is optional and data member is a data type(int, char, float )example

union book {
  int sr;
  char name[10];
  float price;
};

accessing of union member in C++

As members of the union, we access the dot operator as a structure with the union-variable.

Here is the syntax, to access union member

union_name.member_name;

let’s understand this, with the help of an example here

Example

 union book {
   int sr;
   char name[10];
   float price;
 }vr;

now, accessing these data members of a union will be as follows,

  vr.sr;
  vr.name;
  vr.price;

Its program is given below-

Example of union in C++

#include<iostream>
using namespace std;
union book{     
  int sr;
  char name[20];
  float price;
 };

int main()
{
   book vr;

  cout<<"Enter Serial No.: ";
  cin>>vr.sr;
  cout<<"Enter Book Name : ";
  gets(vr.name);
  cout<<"Enter Book Price: ";
  cin>>vr.price;

  cout<<"\nSerial No.: "<<vr.sr;    // garbage value will be print
  cout<<"\nBook Name : "<<vr.name;   // garbage value will be print
  cout<<"\nBook Price: "<<vr.price;  // accurate value be print
return 0;
}

OUTPUT

Serial No.: 101
Book Name : Science
Book Price: 350.5

Serial No.: 16384
Book Name : 
Book Price: 350.5

If we want, we can access the union member using arrow-operator (->) just like in structure.

Found out a union size in C++

Because the memory location of all the data members of the union is the same, so it takes the memory space of the size of that data member, the size of the data member which is more than the other member.

union {
   int no;
   char name[20],
   float price;
 };

In this, the size of the member, name is more than the size of other members (sr, price) so the size of a union in memory (char × 20 = 20 byte) will be 20 bytes.

we can understand this with the help of the program given below, in which we have found the size of the union variable using the sizeof operator.

#include<iostream>
#include<stdio>
using namespace std;

union {                           // union declaration in global
   int sr;
   char name[20];
   float price;
}vr;

int main()
{
   cout<<"Size of union variable : "<<sizeof(vr)<<" byte";
return 0;
}

OUTPUT

Size of union variable : 20 byte

Found out structure size in C++

anonymous union in C++

when we define a union without any name, it is called anonymous union. In this, union members are directly accessed by their names. Note that this type of union is declared (locally) within void main() itself.

int main()
 {
   union {
       ........
       ........
     }
   ........
 }

You can understand this with the help of the program given below,

#include<iostream>
using namespace std;
int main()
  {
    union {                   //declare union in local
       int sr;
       char name[20];
       float price;
     };

   cout<<"Serial No.: ";
   cin>>sr;
   cout<<"Book Name : ";
   cin>>name;
   cout<<"Book Price: ";
   cin>>price;

   cout<<"\nSerial No.: "<<sr;  // garbage value print
   cout<<"\nBook Name : "<<name; //garbage value print
   cout<<"\nBook Price: "<<price;  // accurate value print 

return 0;
}

OUTPUT

Serial No.: 101
Book Name : Science
Book Price: 350.5

Serial No.: 16384
Book Name : 
Book Price: 350.5

similarities between structure and union in C++

  • Both union and structure are user-defined data-types.
  • Both union and structure name are identifiers i.e anyone suitable name (except reserved keyword).
  • like structure, data types in union are declared within the parenthesis bracket. Those are called members and each member .terminates with a semicolon.
  • Members of both structure and union can be of both data-type and function-type.
  • The data members of both, are accessed using their variables along with their member name,
              variable-name.member-name;
  • more than one variable of both can be declared.
             structure-name.variable1, variable2, variable3;
             union-name.variable1, variable2, variable3;
  • In both data-type, the space in memory is reserved only after the variable declared, that is during member declaration the memory can’t reserve.
  • we can declare both data types as globally and locally.

Difference between union and structure in C++

    • As we know, in both, the memory space is reserved only after the variable declaration but where the structure provides a different memory location to all its members in memory, the union members are stored in memory in the same location. here is a diagram.
    • In union, the second value removes the first value, i.e the value entered in the last is stored in the memory, whereas there is nothing like this due to the different memory location in the structure.
  • Structure reserves the space in memory to its members according to their data type, while union takes the size in its data members according to the member whose size is more than other data members. view these two

found out structure size in C++
found out union size in C++

  • The data members of the locally declare union can be accessed by direct members name (called anonymous union) while in either structure local or global we access its data members with structure variable.

Previous – Structure in C++

Next – Pointer in C++

Like it?

Leave a Reply

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

Exit mobile version