MISRA.INIT.MULTIPLE.2012An element of an object is initialized more than once.
MISRA C 2012 Rule 9.4: An element of an object shall not be initialized more than onceCategory: Required Analysis: Decidable, Single Translation Unit Applies to: C99 AmplificationThis rule applies to init ializers for both objects and subobjects. The provision of designated initializers in C99 allows the naming of the components of an aggregate (structure or array) or of a union to be initialized within an initializer list and allows the object’s elements to be initialized in any order by specifying the array indices or structure member names they apply to (elements having no initialization value assume the default for uninitialized objects). RationaleCare is required when using designated initializers since the initialization of object elements can be inadvertently repeated leading to overwriting of previously initialized elements. The C99 Standard does not specify whether the side effects in an overwritten initializer occur or not although this is not listed in Annex J. In order to allow sparse arrays and structures, it is acceptable to only initialize those which are necessary to the application. ExampleArray initialization: /* * Required behaviour using positional initialization * Compliant - a1 is -5, -4, -3, -2, -1 */ int16_t a1[ 5 ] = { -5, -4, -3, -2, -1 }; /* * Similar behaviour using designated initializers * Compliant - a2 is -5, -4, -3, -2, -1 */ int16_t a2[ 5 ] = { [ 0 ] = -5, [ 1 ] = -4, [ 2 ] = -3, [ 3 ] = -2, [ 4 ] = -1 }; /* * Repeated designated initializer element values overwrite earlier ones * Non-compliant - a3 is -5, -4, -2, 0, -1 */ int16_t a3[ 5 ] = { [ 0 ] = -5, [ 1 ] = -4, [ 2 ] = -3, [ 2 ] = -2, [ 4 ] = -1 }; In the following non-compliant example, it is unspecified whether the side effect occurs or not: uint16_t *p; void f ( void ) { uint16_t a[ 2 ] = { [ 0 ] = *p++, [ 0 ] = 1 }; } Structure initialization: struct mystruct { int32_t a; int32_t b; int32_t c; int32_t d; }; /* * Required behaviour using positional initialization * Compliant - s1 is 100, -1, 42, 999 */ struct mystruct s1 = { 100, -1, 42, 999 }; /* * Similar behaviour using designated initializers * Compliant - s2 is 100, -1, 42, 999 */ struct mystruct s2 = { .a = 100, .b = -1, .c = 42, .d = 999 }; /* * Repeated designated initializer element values overwrite earlier ones * Non-compliant - s3 is 42, -1, 0, 999 */ struct mystruct s3 = { .a = 100, .b = -1, .a = 42, .d = 999 }; |