13

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?

aCuria
  • 6,935
  • 14
  • 53
  • 89

2 Answers2

19

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.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
  • 1
    +1, more complete than my answer, even if slightly off on a few points. You might want to use the phrase "constant expression" though rather than "constants", since the former has an official definition in the C language, and makes it clear that complex expressions can satisfy the requirement as long as their constituent components are "sufficiently constant". – R.. GitHub STOP HELPING ICE May 25 '11 at 23:34
6

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 };).

R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711