Dill Dill - 1 year ago 108
C Question

"initializer element is not constant" using designated initializer on static struct with C99

Can someone explain this behavior?

Using the compiler flag

I get the following errors:

  • "initializer element is not constant" for b1.

  • "expected expression before '.' token" for b2

  • b3 is OK.

When not using
all lines are OK.
When not using static b1 is ok.
I'm using GCC.

typedef struct A_tag {
int v;
int w;
} A;

typedef struct B_tag {
A super;
int x;
int y;
} B;

void test(){
static B b1 = ((B){.super={.v=100}, .x=10});
static B b2 = ({.super={.v=100}, .x=10});
static B b3 = {.super={.v=100}, .x=10};

Answer Source

(B){.super={.v=100}, .x=10} is not a "cast" but as a whole this is a "compound literal" a temporary object that only lives inside the corresponding expression (basically). Since this is not a constant but a temporary object, by the standard you can't initialize with it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download