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?
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.
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 };
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With