With this definition
struct A {
int x;
};
why is
struct A a = {0};
valid syntax while
struct A a;
a = {0};
produces the error, "expected expression before '{' token"?
If I replace that line with
a = (struct A){0};
then everything is fine so it's not a problem with assigning to structures.
CodePudding user response:
The curly brace syntax {}
designates an initializer list, and such a list can only be used in an initialization.
In this case:
struct A a = {0};
a
is being declared and initialized with {0}
and is valid syntax.
This is not valid:
a = {0};
Because this is an expression an initializer list can't appear in an expression.
This:
a = (struct A){0};
Is not a cast but an example of a compound literal. The syntax is similar to that of a cast, but what it is doing instead is creating an object of type struct A
and giving an initializer for it. This object is then assigned to a
.
CodePudding user response:
You can only use initializers in a declaration, so statement a = {0};
is invalid.
In statement a = (struct A){0};
you are actually assigning using a compound literal expression, which is valid.