Fork me on GitHub


[C] Error “initializer element is not constant” and static

嘗試著要在  static 的 struct 成員指向其他 struct 的時候 (也就是巢狀 struct),必須注意成員必須是 const,而 C 和 C++ 的 const 語意有所出入,需注意之!

It has to do with C language. In C language objects with static storage duration has to be initialized with constant expressions or with aggregate initializers containing constant expressions.
A "large" object is never a constant expression in C, even if the object is declared as const.
Moreover, in C language the term "constant" refers to literal constants (like 1,'a'0xFF and so on). Const-qualified objects (of any type) are not constants in C language terminology. They cannot be used in initializers of objects with static storage duration, regardless of their type.
For example, this is NOT a constant
const int C = 5; /* not a constant in C */
It would be a constant in C++, but it is not a constant in C. So, if you try doing
static int j = C; /* ERROR */
you will get the same error: an attempt to initialize a static object with a non-constant.
-- EOF --

No comments:

Post a Comment