MISRA C++:2008 Rule 9-5-1
Unions shall not be used
Description
Rule Definition
Unions shall not be used.
Rationale
Using unions to store a value might result in misinterpretation of the value and lead to undefined behavior. For instance:
union Data{ int i; double d; }; void bar_int(int); void bar_double(double); void foo(void){ Data var; var.d = 3.1416; bar_int(var.d);//Undefined Behavior }
bar_int
, the double
data in the union is
misinterpreted as an int
, which is undefined behavior. Compilers might
react to this misinterpretation differently depending on their implementation. To avoid
undefined behaviors, do not use a union
.In some cases, use of unions might be necessary to increase efficiency. In such cases,
use unions after documenting the relevant implementation-defined compiler behaviors. In the
preceding case, before using a union
, consult the manual of the compiler
that you use and document how the compiler reacts to interpreting a
double
as an int
.
Polyspace Implementation
Polyspace® flags the declaration of a union
. You might consider the
use of union
necessary or acceptable in your code. In such cases, justify
the violation by annotating the result or by using code comments. See:
Address Results in Polyspace User Interface Through Bug Fixes or Justifications if you review results in the Polyspace user interface.
Address Results in Polyspace Access Through Bug Fixes or Justifications (Polyspace Access) if you review results in a web browser.
Annotate Code and Hide Known or Acceptable Results if you review results in an IDE.
Troubleshooting
If you expect a rule violation but Polyspace does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.
Examples
Check Information
Group: Classes |
Category: Required |
Version History
Introduced in R2013b