Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Designated initialization of initialized struct

Tags:

c++

c

struct

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).

like image 905
Amomum Avatar asked Dec 16 '22 05:12

Amomum


1 Answers

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.

like image 86
Angew is no longer proud of SO Avatar answered Jan 01 '23 01:01

Angew is no longer proud of SO