Main Content

MISRA C:2012 Rule 9.4

An element of an object shall not be initialized more than once

Description

Rule Definition

An element of an object shall not be initialized more than once.

Rationale

Designated initializers allow explicitly initializing elements of objects such as arrays in any order. However, using designated initializers, one can inadvertently initialize the same element twice and therefore overwrite the first initialization.

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 a[5] = {-2,-1,0,1,2};               /* Compliant */
    int b[5] = {[0]=-2, [1]=-1, [2]=0, [3]=1, [4]=2}; /* Compliant */
    int c[5] = {[0]=-2, [1]=-1, [1]=0, [3]=1, [4]=2}; /* Non-compliant */

}

In this example, the rule is violated when the array element c[1] is initialized twice using a designated initializer.

struct myStruct {
    int a;
    int b;
    int c;
    int d;
};

void func(void) {
    struct myStruct struct1 = {-4,-2,2,4}; /* Compliant */
    struct myStruct struct2 = {.a=-4, .b=-2, .c=2, .d=4}; /* Compliant */
    struct myStruct struct3 = {.a=-4, .b=-2, .b=2, .d=4}; /* Non-compliant */
}

In this example, the rule is violated when struct3.b is initialized twice using a designated initializer.

Check Information

Group: Initialization
Category: Required
AGC Category: Required

Version History

Introduced in R2014b

expand all