Given the following:
struct example_struct
{
char c;
int i;
};
Is any the following initializer syntax valid in C99?
Syntax example #1
struct example_struct example = { 'a', .i = 1};
Syntax example #2
struct example_struct example = { .c = 'a', 1};
I am writing a simple struct parser and in my testing, this does not cause a compiler error using XCode 4.2. I would like my parser to be C99 compliant. My understanding (without a standard reference) is that a struct initializer should either have all unnamed or named (i.e. designated) members.
Should syntax example #1 and #2 be compiler errors?
If the examples are valid, what are the rules for the initialization syntax?
UPDATED QUESTION EXAMPLES
struct example_struct_3
{
char c;
int i;
float f;
};
struct example_struct_3 example = { .i = 1, 1.0};
In the same main question, how would example three work? I'm mainly confused about the arbitrary ordering of designated initializers with standard initializers.
Both your initializations example 1 and 2 are valid C99/C11 initializations. You can mix designation initializers and non-designation initializers in an initializer list.
EDIT: regarding your new example 3, the initialization is also valid. After initialization, example.c
has value 0
, example.i
has value 1
and example.f
has value (float) 1.0
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With