Search

How to use Unions in C++ ?

Save memory space!


How to use Unions in C++ ?


What is a Union?

A union is similar to a struct, the difference is that Union reuses the space for the next type given inside it, whereas Struct adds it to a new block.

Declaration of a Union:

union Name {
  // contents
};

It is also similar to classes, but apart from the reuse difference, like Structs, Union doesn’t need public to access data, in classes if you don’t inform it will be private by default.


Examples

Let’s suppose you have this code that stores data for a certain product:

#include <iostream>

union Product {
  int id;
  double value;
};

int main( int argc , char **argv ){
  Product p;
  p.id = 9;
  std::cout << p.id << '\n';
  return 0;
}


If you compile the code above, notice that the output will be just the id we assigned: 9 .

But now let’s also assign data to the value and print:

#include <iostream>

union Product {
  int id;
  double value;
};

int main( int argc , char **argv ){
  Product p;
  p.id = 9;
  p.value = 1,542;
  std::cout << p.id << '\n';
  std::cout << p.value << '\n';
  return 0;
}

Output:

824633721
1.542

Note that the value output was correct, but the id turned into a strange number.

Also note that if you use this same code with struct this will not happen, for example:

#include <iostream>

struct Product { // change to struct
  int id;
  double value;
};

int main( int argc , char **argv ){
  Product p;
  p.id = 9;
  p.value = 1,542;
  std::cout << p.id << '\n';
  std::cout << p.value << '\n';
  return 0;
}

Output:

9
1.542

Why ???

As I said, union reuses the space, that is, the int (4 bytes) is smaller than the double (8 bytes), so that reused space becomes a Memory Garbage .

Let’s illustrate for didactic purposes only:


In a union the int space is reused and it writes the double: Union


In a struct it keeps that int space and creates a new one for the double Struct


If you reverse the definition orders this will not happen because int is smaller than double .

Unions were created precisely to save memory space, but programmers have gotten a writing addiction and more commonly use Structs.

However, in code from some programmers who care a lot about optimization you will find more Unions than Structs .


Useful links


cpp cppdaily


Share



Comments