Main Content

MISRA C:2023 Rule 9.3

Arrays shall not be partially initialized

Since R2024a

Description

Rule Definition

Arrays shall not be partially initialized.

Rationale

Providing an explicit initialization for each array element makes it clear that every element has been considered.

Polyspace Implementation

The checker reports a violation of this rule if an array is partially initialized at declaration. The checker allows initialization of all values using the shorthand notation {0}, for instance:

float dat2[3*3] = {0};

Troubleshooting

If you expect a rule violation but do not see it, refer to Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

void func(void) {
    int x[3] = {0,1,2};               /* Compliant */
    int y[3] = {0,1};                 /* Non-compliant */
    int z[3] = {0};                   /* Compliant - exception */
    int a[30] = {[1] = 1,[15]=1};     /* Compliant - exception */
    int b[30] = {[1] = 1, 1};         /* Non-compliant */
    char c[20] = "Hello World";       /* Compliant - exception */
}

In this example, the rule is not violated when each array element is explicitly initialized.

The rule is violated when some elements of the array are implicitly initialized. Exceptions include the following:

  • The initializer has the form {0}, which initializes all elements to zero.

  • The array initializer consists only of designated initializers. Typically, you use this approach for sparse initialization.

  • The array is initialized using a string literal.

Check Information

Group: Initialization
Category: Required
AGC Category: Readability

Version History

Introduced in R2024a