Compilation error C2099: initializer is not a constant

The following code will not compile:

const int a = 0; struct Test { int b; }; static const struct Test test = { a }; 

Its a shortened example of what I'm really trying to do, but what am I doing wrong?

+6
source share
2 answers

In the C89 / 90 version of the C language, all aggregated initializers should consist only of constants. In C terminology, a constant of type int is a literal value, for example 10 , 20u , 0x1 , etc. Enum members are also constants. Variables of type const int are not constants in C. You cannot use the variable const int in an aggregate initializer. (For this reason, in C, when you need to declare a named constant, you must use either #define or enum , but not a const qualifier.)

In C99, this requirement for aggregate initializers has been relaxed. Now you can use non-constants in aggregate initializers of local objects. However, for static objects (as in your example), the requirement still persists. So, even in C99 you have to either use

 #define a 0 

or use the enum name constant as indicated by @R ..

+11
source

a not a constant expression. This is a const -qualified variable. If you want to use a symbolic name that you can use in constant expressions, you need either a preprocessor macro ( #define a 0 ) or an enumeration ( enum { a = 0 }; ).

+6
source

Source: https://habr.com/ru/post/889046/


All Articles