Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compile error C2099: initializer is not a constant [duplicate]

The following code wont compile:

const int a = 0;

struct Test
{
    int b;
};

static const struct Test test = 
{
    a
};

Its a cut down example of what I am really trying to do, but what am I doing wrong?

like image 666
aCuria Avatar asked May 25 '11 21:05

aCuria


2 Answers

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

In C99 this requirement for aggregate initializers was relaxed. It is now OK to use non-constants in aggregate initializers of local objects. However, for static objects (as in your example) the requirement still holds. So, even in C99 you'l' have to either use

#define a 0

or use a named enum constant as suggested in @R..'s answer.

like image 82
AnT Avatar answered Oct 09 '22 19:10

AnT


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

like image 29
R.. GitHub STOP HELPING ICE Avatar answered Oct 09 '22 19:10

R.. GitHub STOP HELPING ICE