Home > Enterprise >  Why is this type of C99 struct initialisation not allowed?
Why is this type of C99 struct initialisation not allowed?

Time:12-18

Why is this type of C99 struct initialisation not allowed? If (not) possible, please explain.

struct Point {int x; int y;};
struct Data {struct Point p;};
struct Data data = {0};
data.p = {.x = 2, .y = 4};

However, this is allowed:

struct Point {int x; int y;};
struct Data {struct Point p;};
struct Data data = {0};
struct Point p = {.x = 2, .y = 4};
data.p = p;

Edit: data = {} -> data = {0}

CodePudding user response:

Neither code sample is allowed in strictly conforming C; the grammar requires that there be at least one initializer inside the braces, so struct Data data = {}; is incorrect. (It can be corrected to struct Data data; or struct Data data = {0};.)

data.p = {.x = 2, .y = 4}; is an assignment, not initialization. In the standard C grammar, the right operand of an assignment must be an expression (specifically an assignment-expression). The source code {.x = 2, .y = 4} is not an expression; there is no expression that starts with {. The source code p is an expression, so it can be the right operand of an assignment.

You can use data.p = (struct Point) {.x = 2, .y = 4};. In this , (struct Point) {.x = 2, .y = 4} is a compound literal, which does form an expression.

  • Related