Search code examples
cvisual-studio-2010

compile error C2099: initializer is not a constant


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?


Solution

  • 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.