noinput
noinput

Reputation: 411

struct member 'Initializer element is not a compile-time constant'

struct S {
   int a;
};

int a = ((struct S) {8}).a;

the compiler reports an error "Initializer element is not a compile-time constant", why ?

Upvotes: 2

Views: 5318

Answers (1)

noelicus
noelicus

Reputation: 15055

Because that struct in the brackets is actually a run-time thing. You can only assign constants to a global on initialization. e.g.

 int a = 8;

You cannot do this with globals:

int b = 8;
int a = b; // Because b is a run-time variable

Often this technique is used for defining global constants:

#define MY_CONSTANT 8
// Then somewhere else you can use it...
int a = MY_CONSTANT;
// or
struct S s = {MY_CONSTANT};

Upvotes: 5

Related Questions