. Advertisement .
..3..
. Advertisement .
..4..
As advised, I used some code samples in another forum, but it could not improve the problem. My question is the “error: initializer element is not constant” in c-how to solve it? The command line is:
typedef struct foo_t {
int a, b, c;
} foo_t;
const foo_t foo_init = { 1, 2, 3 };
foo_t my_foo = foo_init;
int main()
{
return 0;
}
#define foo_init { 1, 2, 3 }
and the result:
Error: initializer element is not constant
What does the message mean? Can you advise me to fix it? If you have other better answers, leave them in the answer box below.
The cause:
This error happens due to you are trying to initialize an element, but it is not a constant in C.
Constant expressions or aggregate initializers that contain constant expressions must be used to initialize C language objects with static storage duration.
Even if the object has been declared as
const
, a “large” object will never be a constant expression within C.In C language, the term constant refers to literal constants, such as
1
,'a'
,0xFF
,..), enum members and results of operators likesizeof
. Const-qualified objects of any type are and not constants according to C language terminology. They are not permitted to be used in initializers for objects with static storage duration regardless of type.For example:
N
above is considered as a constant for C++, but not for C.The same error will happen if you try to initialize a static item with a non-constant.
Solution:
In C language you have to use
#define
for declaring named variables and creating named aggregate initializers.It is a limitation of the language. Section 6.7.8/4
Section 6.6 defines what constant expressions must be considered. It does not state in any place that a const variable should be considered constant expression. Although it is legal for a compiler (
6.6/10 - An implementation may accept other forms of constant expressions
), this would restrict portability.You would be fine if you could change
my_foo
to not have static storage