Main Content

AUTOSAR C++14 Rule M8-5-2

Braces shall be used to indicate and match the structure in the non-zero initialization of arrays and structures

Description

Rule Definition

Braces shall be used to indicate and match the structure in the non-zero initialization of arrays and structures.

Rationale

The use of nested braces in initializer lists to match the structures of nested objects in arrays, unions, and structs encourages you to consider the order of initialization of complex data types and makes your code more readable. For example, the use of nested braces in the initialization of ex1 makes it easier to see how the nested arrays arr1 and arr2 in struct ex1 are initialized.

struct Example
{
    int num;
    int arr1[2];
    int arr2[3];
};

//....
struct Example ex1 {1, {2, 3}, {4, 5, 6}}; //Compliant

The rule does not require the use of nested braces if you zero initialize an array, a union, or a struct with nested structures are the top-level, for instance:

struct Example ex1 {}; //Compliant

Polyspace Implementation

If you non-zero initialize an array, union, or struct that contains nested structures and you do not use nested braces to reflect the nested structure, Polyspace® flags the first element of the first nested structure in the initializer list. For instance, in this code snippet, Polyspace flags the number 2 because it corresponds to the first element of nested structure arr1 inside struct ex1.

struct Example
{
    int num;
    int arr1[2];
    int arr2[3];
};

//....
struct Example ex1 {1, 2, 3, 4, 5, 6}; // Non-compliant

Polyspace does not report violations of this rule on containers implemented by the standard template library (STL).

Troubleshooting

If you expect a rule violation but Polyspace does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

char arr1[2][3] {'a', 'b', 'c', 'd', 'e', 'f'}; //Non-compliant
char arr2[2][3] {{'a', 'b', 'c'}, {'d', 'e', 'f'}}; //Compliant
char arr_top_level[2][3] { }; //Compliant
char arr_sub_level[2][3] { {}, {'d', 'e', 'f'}}; //Non-compliant

In this example, two-dimensional array arr1 is non-compliant because the initializer list does not reflect the nested structure of this array (two arrays of three elements each). The initialization of arr2 uses nested braces to reflect the nested structure of the array and is compliant. Similarly, the initialization of arr_top_level is compliant because it zero initializes the array at the top level. Note that the initialization of arr_sub_level is non-compliant because zero-initializes only the first sub-array while explicitly initializing all the elements of the other sub-array.

Check Information

Group: Declarators
Category: Required, Automated

Version History

Introduced in R2019a

expand all