编译错误C2099:初始化不是一个常数
以下code编译习惯:
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?
在C89 / 90版本的C语言的所有集合初始化器必须包含的常量的唯一。在C语言术语不变 INT
的的 的类型是文字值,如 10
, 20U
,为0x1
等枚举成员也是常数。 const int的
类型的变量的不的C语言常量不能使用 const int的
合计初始化变量。 (由于这个原因,在C语言中,当你需要声明一个命名常量,你应该使用的#define
或枚举
,而不是常量
预选赛。)
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.)
在C99这一要求的骨料初始化很轻松。它现在确定在本地对象的集合体初始化使用非常数。然而,对于静态物体(如你的例子)的要求仍然有效。因此,即使在C99 you'l'必须要么使用
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
或使用命名为@R建议枚举常量..的答案。
or use a named enum constant as suggested in @R..'s answer.