AutosarC++18_03-A9.5.1

Unions shall not be used

Required inputs: IR

Rationale

Unions are not type safe and their usage can be misleading and easily misinterpreted by developers.

Exceptions

It is allowed to use tagged unions until std::variant is available in the C++ Standard Library (C++17)

Example
// $Id: A9-5-1.cpp 305588 2018-01-29 11:07:35Z michal.szczepankiewicz $

#include <cstdint>
// Compliant
struct Tagged {
  enum class TYPE { UINT, FLOAT };
  union {
    uint32_t u;
    float f;
  };
  TYPE which;
};

int main(void) {
  Tagged un;

  un.u = 12;
  un.which = Tagged::TYPE::UINT;

  un.u = 3.14f;
  un.which = Tagged::TYPE::FLOAT;

  return 0;
}
See Also
  • MISRA C++ 2008 [6]: M9-5-1: Unions shall not be used
  • JSF December 2005 [7]: AV Rule 153: Bit-fields shall have explicitly unsigned integral or enumeration types only
  • C++ Core Guidelines [10]: C.181: Avoid “naked” unions
  • C++ Core Guidelines [10]: C.182: Use anonymous unions to implement tagged unions
  • C++ Core Guidelines [10]: Type.7: Avoid naked union: Use variant instead.

Possible Messages

Key

Text

Severity

Disabled

union

Unions shall not be used

None

False

Options

allow_tagged_unions

allow_tagged_unions : bool = True

Whether tagged unions (nested in a struct that has an enum discriminator) should be allowed.