Rule Definition
The use of unions to access an object in different ways may result in the data being misinterpreted.
Therefore, this rule prohibits the use of unions for any purpose.
It is recognized nonetheless that there are situations in which the careful use of unions is desirable in constructing an efficient implementation. In such situations, deviations to this rule are considered acceptable provided that all relevant implementation-defined behaviour is documented. This might be achieved in practice by referencing the implementation section of the compiler manuals from the design documentation.
Remediation
In case it is desired to use Unions it is strongly advised to create a deviation.
Violation Code Sample
namespace NS1
{
// Compliant - no union
}
namespace NS2
{
union U1 // Non-compliant – union
{
int32_t i;
float32_t j;
};
}
Reference
MISRA C++, 2008, 9-5-1: Unions shall not be used
AUTOSAR C++, 2014, M9-5-1: Unions shall not be used
Related Technologies
Technical Criterion
Programming Practices - Unexpected Behavior
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.