Dill Dill - 2 months ago 14
C Question

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

Can someone explain this behavior?

Using the compiler flag

std=c99
I get the following errors:


  • "initializer element is not constant" for b1.

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

  • b3 is OK.



When not using
-std=c99
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

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