Why is this an issue?
ISO/IEC 14882:2003 [1] requires initializer 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 developer to explicitly consider and demonstrate the order in which elements of complex data types are initialized (e.g.
multi-dimensional arrays).
The zero initialization of arrays or structures shall only be applied at the top level.
The non-zero initialization of arrays or structures requires an explicit initializer for each element.
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 initialized (to zero or NULL) by giving an explicit initializer for the first
element only. If this method of initialization is chosen then the first element should be initialized to zero (or NULL), and nested braces need not be
used.
Noncompliant code example
int a1[3][2] = { 1, 2, 3, 4, 5, 6 }; // Noncompliant
int a2[5] = { 1, 2, 3 }; // Noncompliant, partial initialization
int a3[2][2] = { { }, { 1, 2 } }; // Noncompliant, zero initialization at sub-level
Compliant solution
int a1[3][2] = { { 1, 2 }, { 3, 4 }, { 5, 6 } }; // Compliant
int a2[5] = { 1, 2, 3, 0, 0 }; // Compliant, Non-zero initialization
int a2[5] = { 0 }; // Compliant, zero initialization
int a3[2][2] = { }; // Compliant, zero initialization
Resources
- MISRA C:2004, 9.2 - Braces shall be used to indicate and match the structure in the non-zero initialization of arrays and structures.
- MISRA C++:2008, 8-5-2 - Braces shall be used to indicate and match the structure in the nonzero initialization of arrays and structures.
- MISRA C:2012, 9.2 - The initializer of an aggregate or union shall be enclosed in braces.
- MISRA C:2012, 9.3 - Arrays shall not be partially initialized.