MISRA Discussion Forums
named vs positional initialization - Printable Version

+- MISRA Discussion Forums (https://forum.misra.org.uk)
+-- Forum: MISRA C (https://forum.misra.org.uk/forumdisplay.php?fid=4)
+--- Forum: MISRA C:2012 and MISRA C:2023 guidelines (https://forum.misra.org.uk/forumdisplay.php?fid=21)
+---- Forum: 8.9 Initialization (https://forum.misra.org.uk/forumdisplay.php?fid=164)
+---- Thread: named vs positional initialization (/showthread.php?tid=1751)



named vs positional initialization - delirium5223 - 04-09-2025

What do you think about advising against using mixed aggregate initialization, named vs positional.

When mixing them there is a higher chance for human confusion/mistake. e.g. not covering all of them etc



Code:
typedef struct
{
  int x;
  int y;
  int z;
} TypeA;

void test4(void)
{
  TypeA obj = { .y = 2, 3 }; // nok mixed aggregate initialization, named vs positional
  TypeA obj2 = { 3 , .y = 2 }; // nok
  TypeA obj3 = { 3 , 2, 4 }; //ok, not mixed
  TypeA obj4 = { .x = 3 , .z = 4, .y = 2 }; //ok, not mixed
}

Rule 9.6 only prohibits them when they are embedded structs, not for single struct.

Code:
/* Non-compliant - chained designators and implicit positional initializers mixed */
struct T tt = {
1,
.s.x = 2, /* To a human reader, this looks like .z is being initialized */
3, /* tt is actually initialized as { 1, { 2, 3 }, 0 } */
}; /* This also violates Rule 9.2 */