Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) union

 

union is a C++ keyword to declare a struct that uses the same memory for all elements.

 

In the example below, a union is created consisting of a double and an int. When the int is modified, the double is modified as well (and vice versa).

 

 

#include <boost/static_assert.hpp>
#include <iostream>

struct Struct
{
  double d;
  int i;
};

union Union
{
  double d;
  int i;
};

int main()
{
  //Check that a unions' size is
  //smaller than a struct's
  BOOST_STATIC_ASSERT(sizeof(Union)<sizeof(Struct));

  //Create a clean union
  Union u;
  u.i = 0;
  u.d = 0;

  u.i = 1000;
  std::cout
    << "int   : " << u.i << '\n'
    << "double: " << u.d << '\n';
  u.d = 1000.0;
  std::cout
    << "int   : " << u.i << '\n'
    << "double: " << u.d << '\n';

}

 

Screen output:

 

int : 1000 double: 4.94066e-321 int : 0 double: 1000

 

Consider never using unions [1]. Use unions to save space [2]. Never use unions for type conversion [2].

 

 

 

 

 

References

 

  1. Joint Strike Fighter Air Vehicle C++ Coding Standards for the System Development and Demonstration Program. Document Number 2RDU00001 Rev C. December 2005. AV Rule 153 (MISRA Rule 110, Revised): 'Unions shall not be used.'
  2. Bjarne Stroustrup. The C++ Programming Language (4th edition). 2013. ISBN: 978-0-321-56384-2. Chapter 8.5. Advice. page 224: '[4] Use unions to save space (represent alternatives and never for type conversion'

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict