c - does nested struct initialization depend on scope? -


i can't figure out. why compile:

typedef struct {     int foo[3]; } a_t;  typedef struct b {     char tag;     a_t foo; } b_t;  const a_t default_a = { { 1, 2, 3 } };  int main(int argc, char **argv) {     const b_t default_b = { 'a', default_a };     return 0; } 

and not:

typedef struct {     int foo[3]; } a_t;  typedef struct b {     char tag;     a_t foo; } b_t;  const a_t default_a = { { 1, 2, 3 } };  const b_t default_b = { 'a', default_a };  int main(int argc, char **argv) {     return 0; }   > gcc tp.c tp.c:13:1 error: initializer element not constant tp.c:31:1 error: (near initialization ...default_b.foo...) 

the change scope of declaration default_b. why make difference? can tell, either both valid, or should both wrong. gcc (v4.7.3) accepts first , not second. driving me nuts.

[[edit]] follow-up question bonus points: given second program not compliant c standard, how may accomplish same thing in standard-compliant way? ie: global, constant definition of default_b includes value of default_a.

c language specification requires object static storage duration initialized constant expression.

in first code segment, default_b has automatic storage duration while in second 1 has static storage duration due being defined @ file scope. second program violates rule:

c11, 6.7.9 initialization

all expressions in initializer object has static or thread storage duration shall constant expressions or string literals.

the qualifier const not mean it's constant expression rather should read read-only. constant expression can evaluated @ compile time:

6.6 constant expressions

a constant expression can evaluated during translation rather runtime, , accordingly may used in place constant may be.


Comments

Popular posts from this blog

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

php - render data via PDO::FETCH_FUNC vs loop -

The canvas has been tainted by cross-origin data in chrome only -