Designated initialization of initialized struct

2020-04-08 14:20发布

问题:

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

回答1:

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.



回答2:

Designated Initializer(in the first example) and Compound Literals(in the second example), are both introduced in C99, C++ doesn't support them yet.

However, some compiler may support these features in C++ as an extension. For instance, gcc supports Compound Literals in C++ but not Designated Initializer. It seems that your compiler does the same.



回答3:

Designated Initializers are a C99 feature but it seems like clang and gcc support them in C++ as an extension although the gcc doc claims otherwise. If I build this with clang using the -pedantic flag it says:

warning: designated initializers are a C99 feature [-Wc99-extensions]

and gcc warns:

 warning: ISO C++ does not allow C99 designated initializers [-Wpedantic]

In C++ we have constructors which will allow you to initialize a struct in a cleaner manner.

The second example uses Compound Literals and this is also a C99 feature that is supported as an extension.



标签: c++ c struct