Main Content

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
} 
In the call to 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:

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

expand all

#include <iostream>

union Pi{ //Noncompliant
	int i;
	double d;
};

void foo(void){

	std::cout << std::endl;

	Pi pi;
	pi.d = 3.1416;// pi holds a double
	std::cout << "pi.d: " << pi.d << std::endl;     
	std::cout << "pi.i: " << pi.i << std::endl;      // Undefined Behavior

	std::cout << std::endl;

	pi.i = 4;     // pi holds an int
	std::cout << "pi.i: " << pi.i << std::endl;
	std::cout << "pi.d: " << pi.d << std::endl;      // Undefined Behavior

	std::cout << std::endl;

}

In this example, the union Pi contains a double and an int. In the code, a double is misinterpreted as an int and vice versa by using the union. These misinterpretations are undefined behaviors and might lead to bugs and implementation dependent code behavior. Polyspace flags the union declaration.

Check Information

Group: Classes
Category: Required

Version History

Introduced in R2013b