MISRA.INIT.BRACES.2012The initializer for an aggregrate or union shall be enclosed in braces.
MISRA C 2012 Rule 9.2: The initializer for an aggregate or union shall be enclosed in bracesCategory: Required Analysis: Decidable, Single Translation Unit Applies to: C90, C99 AmplificationThis rule applies to initializers for both objects and subobjects. An initializer of the form { 0 }, which sets all values to 0, may be used to initialize subobjects without nested braces. Note: this rule does not itself require explicit initialization of objects or subobjects. RationaleUsing braces to indicate initialization of subobjects improves the clarity of code and forces programmers to consider the initialization of elements in complex data structures such as multi-dimensional arrays or arrays of structures. Exception
ExampleThe following three initializations, which are permitted by The Standard, are equivalent. The fi rst form is not permitted by this rule because it does not use braces to show subarray initialization explicitly. int16_t y[ 3 ][ 2 ] = { 1, 2, 0, 0, 5, 6 }; /* Non-compliant */ int16_t y[ 3 ][ 2 ] = { { 1, 2 }, { 0 }, { 5, 6 } }; /* Compliant */ int16_t y[ 3 ][ 2 ] = { { 1, 2 }, { 0, 0 }, { 5, 6 } }; /* Compliant */ In the following example, the initialization of z1 is compliant by virtue of Exception 3 because a designated initializer is used to initialize the subobject z1[ 1 ]. The initialization of z2 is also compliant for the same reason. The initialization of z3 is non-compliant because part of the subobject z3[ 1 ] is initialized with a positional initializer but is not enclosed in braces. The initialization of z4 is compliant because a designated initializer is used to initialize the subobject z4[ 0 ] and the initializer for subobject z4[ 1 ] is brace-enclosed. int16_t z1[ 2 ][ 2 ] = { { 0 }, [ 1 ][ 1 ] = 1 }; /* Compliant */ int16_t z2[ 2 ][ 2 ] = { { 0 }, [ 1 ][ 1 ] = 1, [ 1 ][ 0 ] = 0 }; /* Compliant */ int16_t z3[ 2 ][ 2 ] = { { 0 }, [ 1 ][ 0 ] = 0, 1 }; /* Non-compliant */ int16_t z4[ 2 ][ 2 ] = { [ 0 ][ 1 ] = 0, { 0, 1 } }; /* Compliant */ The first line in the following example initializes 3 subarrays without using nested braces. The second and third lines show equivalent ways to write the same initializer. float32_t a[ 3 ][ 2 ] = { 0 }; /* Compliant */ float32_t a[ 3 ][ 2 ] = { { 0 }, { 0 }, { 0 } }; /* Compliant */ float32_t a[ 3 ][ 2 ] = { { 0.0f, 0.0f }, { 0.0f, 0.0f }, { 0.0f, 0.0f } }; /* Compliant */ union u1 { int16_t i; float32_t f; } u = { 0 }; /* Compliant */ struct s1 { uint16_t len; char buf[ 8 ]; } s[ 3 ] = { { 5u, { 'a', 'b', 'c', 'd', 'e', '\0', '\0', '\0' } }, { 2u, { 0 } }, { .len = 0u } /* Compliant - buf initialized implicitly */ }; /* Compliant - s[] fully initialized */ |