Skip to main content

IAR Embedded Workbench for Arm 9.70.x

UNION-type-punning

In this section:
Synopsis

Writing to a field of a union after reading from a different field, effectively re-interpreting the bit pattern with a different type.

Enabled by default

Yes

Severity/Certainty

Medium/High

mediumhigh.png
Full description

Writing to one field of a union and then silently reading from another field circumvents the type system. To reinterpret bit patterns deliberately, use an explicit cast. This check is identical to MISRAC2004-12.12_a.

Coding standards
CERT EXP39-C

Do not access a variable through a pointer of an incompatible type

CWE 188

Reliance on Data/Memory Layout

MISRA C:2004 12.12

(Required) The underlying bit representations of floating-point values shall not be used.

Code examples

The following code example fails the check and will give a warning:

union name {
	int int_field;
	float float_field;
};

void example(void) {
	union name u;
	u.int_field = 10;
	float f = u.float_field;
}

The following code example passes the check and will not give a warning about this issue:

union name {
	int int_field;
	float float_field;
};

void example(void) {
	union name u;
	u.int_field = 10;
	float f = u.int_field;
}