C99 introduced the concept of designated intializers for structs. So for example, given:
typedef struct {
int c;
char a;
float b;
} X;
I could initialize like: X foo = {.a = '\1', .b = 2.0F, .c = 4};
and calling: printf("c = %d\na = %hhu\nb = %f", foo.c, foo.a, foo.b);
would output:
c = 4
a = 1
b = 2.000000
As mentioned here this has the "surprising behavior" of assigning to c
then a
then b
, independent of the order of my designated initializers.
This becomes a real issue if I have functions like this:
int i = 0;
int f() {
return ++i;
}
int g() {
i += 2;
return i;
}
int h() {
i += 4;
return i;
}
And I want to initialize like this: X foo = {.a = (char)f(), .b = g(), .c = h()};
Now when I do: printf("c = %d\na = %hhu\nb = %f", foo.c, foo.a, foo.b);
I get:
c = 4
a = 5
b = 7.000000
The problem being there was no warning that my initialization order was not respected. Is there a warning or something I can enable for this?