[previous] MISRA-C:2004  Rule  18.4:  (Required) [next] Unions shall not be used.
Rule prohibits the reuse of memory areas for unrelated purposes. However, even when memory is being reused for related purposes, there is still a risk that the data may be misinterpreted. Therefore, this rule prohibits the use of unions for any purpose.

It is recognised 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. The kinds of implementation behaviour that might be relevant are:

* padding - how much padding is inserted at the end of the union

* alignment - how are members of any structures within the union aligned

* endianness - is the most significant byte of a word stored at the lowest or highest memory address

* bit-order - how are bits numbered within bytes and how are bits allocated to bit fields

The use of deviations is acceptable for (a) packing and unpacking of data, for example when sending and receiving messages, and (b) implementing variant records provided that the variants are differentiated by a common field. Variant records without a differentiator are not considered suitable for use in any situation.

Example Code:


/* PRQA S 3205 ++ */

#include "misra.h"
#include "m2cmex.h"

union test
{
   S8 *c;
   S32 i;
};

extern S16 test_1804( void )
{
   union test mytest;                  /* MISRA Violation */

   return 0;
}


QAC messages that encompass this guideline:

0750 A union type specifier has been defined.
0759 An object of union type has been defined.



(c) The Motor Industry Research Association, 2004
QA C Source Code Analyser 8.1.2
MISRA-C:2004 Compliance Module 3.2
© 2013 Programming Research
www.programmingresearch.com
Personality Groups | Glossary | Message Index | MISRA-C:2004 Rule Index Contents