[previous] MISRA-C:2004  Rule  9.2:  (Required) [next] Braces shall be used to indicate and match the structure in the non-zero initialisation of arrays and structures.
ISO C requires initialiser lists for arrays, structures and union types to be enclosed in a single pair of braces (though the behaviour if this is not done is undefined). The rule given here goes further in requiring the use of additional braces to indicate nested structures. This forces the programmer to explicitly consider and demonstrate the order in which elements of complex data types are initialised (e.g. multi-dimensional arrays).

For example, below are two valid (in ISO C) ways of initialising the elements of a two dimensional array, but the first does not adhere to the rule:

int16_t y[3][2] = { 1, 2, 3, 4, 5, 6 };              /* not compliant */
int16_t y[3][2] = { { 1, 2 }, { 3, 4 }, { 5, 6 } };  /* compliant     */

A similar principle applies to structures, and nested combinations of structures, arrays and other types.

Note also that all the elements of arrays or structures can be initialised (to zero or NULL) by giving an explicit initialiser for the first element only. If this method of initialisation is chosen then the first element should be initialised to zero (or NULL), and nested braces need not be used.

The ISO standard [2] contains extensive examples of initialisation.

The intent of Rule 9.2 is that the non-zero initialisation of arrays and structures shall require an explicit initialiser for each element, e.g.

int16_t arraya1[5] = { 1, 2, 3, 0, 0 };
/* Compliant - non-zero initialisation */
int16_t arraya2[5] = { 0 };
		/* Compliant - zero initialisation*/
int16_t arraya3[5] = { 1, 2, 3 };
		/* Not Compliant - non-zero initialisation */
int16_t arraya4[2][2] = { 0 };
/* Compliant - zero initialisation at top-level */
int16_t arraya5[2][2] = { { 0 }, { 1, 2 }};
/* Not Compliant - zero initialisation at sub-level */

Zero or NULL initialisation shall only be applied at the top level of the array or structure.


QAC messages that encompass this guideline:

0686 Array has fewer initializers than its declared size. Default initialization is applied to the remainder of the array elements.
0693 Struct initializer is missing the optional {.
0694 Array initializer is missing the optional {.



(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