Rule A9-5-1 (required, implementation, automated)
Unions shall not be used.
Rationale
Unions are not type safe and their usage can be misleading and easily misinterpreted by developers.
Exception
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 [7]: M9-5-1: Unions shall not be used JSF December 2005 [8]: AV Rule 153: Bit-fields shall have explicitly unsigned integral or enumeration types only C++ Core Guidelines [11]: C.181: Avoid “naked” unions C++ Core Guidelines [11]: C.182: Use anonymous unions to implement tagged unions C++ Core Guidelines [11]: Type.7: Avoid naked union: Use variant instead.