Main Content

MISRA C:2023 Rule 13.1

Initializer lists shall not contain persistent side effects

Since R2024a

Description

Rule Definition

Initializer lists shall not contain persistent side effects.

Rationale

C99 permits initializer lists with expressions that can be evaluated only at run-time. However, the order in which elements of the list are evaluated is not defined. If one element of the list modifies the value of a variable which is used in another element, the ambiguity in order of evaluation causes undefined values. Therefore, this rule requires that expressions occurring in an initializer list cannot modify the variables used in them.

Polyspace Implementation

Polyspace® reports a violation whenever an expression occurs within an initializer list and the expression modifies the variables within the expression or contains volatile variables.

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

volatile int v;
int x;
int y;

void f(void) {
    int arr[2] = {x+y,x-y};       // Compliant
    int arr2[2] = {v,v};          // Non-compliant 
    int arr3[2] = {x++,x+y};      // Non-compliant
}

In this example, the rule is not violated in the first initialization because the initializer does not modify either x or y. The rule is violated in the other initializations.

  • In the second initialization, because v is volatile, the initializer can modify v. The initialization of arr2 is different depending on which array element is initialized first.

  • In the third initialization, the initializer modifies the variable x. The initialization of arr3 is different depending on whether x++ is evaluated earlier or later.

Check Information

Group: Side Effects
Category: Required
AGC Category: Required

Version History

Introduced in R2024a