I am aware that I can initialize a structure in C99 with designated initializer, like this:
typedef struct
{
char a;
char b;
int c;
} MyStruct;
MyStruct s = {.a = 1, .b = 2, .c = 3};
(that code isn't working in my c++ compiler, but (russian) wikipedia says it should)
But for some weird reason code like this will also compile (and work as expected):
typedef struct
{
char a;
char b;
int c;
} MyStruct;
MyStruct arr[5];
int main(void)
{
arr[0] = (MyStruct){.a = 1, .b = 2, .c = 0x332211};
}
I supposed that initialization should work only when object is created, not afterwards.
Is it behavior like this normal or is it some kind of compiler quirk? Should it work in C++? What is exactly is this thing in curly braces? Some kind of temporary unnamed structure? I'm using Keil uVision 4 (and designated initializer is not working in c++ mode).
Designated initialisers are a C construct, they're not part of C++. So the C++ compiler is correct in rejecting the code, and should do so in both cases.
The second construct is a "compound literal," again a C feature which is not part of C++. So the C++ compiler should reject that, while a C99 (or newer) compiler should accept both snippets.
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