编译错误 C2099:初始值设定项不是常量
以下代码无法编译:
const int a = 0;
struct Test
{
int b;
};
static const struct Test test =
{
a
};
它是我真正想做的事情的简化示例,但我做错了什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 C 语言的 C89/90 版本中,所有聚合初始值设定项必须仅包含常量。在 C 语言术语中,
int
类型的常量是文字值,例如10
、20u
、0x1
等。枚举成员也是常量。const int
类型的变量在 C 中不是常量。您不能在聚合初始值设定项中使用const int
变量。 (因此,在C语言中,当你需要声明一个命名常量时,你应该使用#define
或enum
,而不是const
限定符。)在 C99 中,聚合初始值设定项的这一要求被放宽。现在可以在本地对象的聚合初始值设定项中使用非常量。但是,对于静态对象(如您的示例中),该要求仍然成立。因此,即使在 C99 中,您也必须使用
或使用 @R.. 的答案中建议的命名枚举常量。
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, like10
,20u
,0x1
etc. Enum members are also constants. Variables ofconst int
type are not constants in C. You can't use aconst int
variable in aggregate initializer. (For this reason, in C language, when you need to declare a named constant you should use either#define
orenum
, but notconst
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
or use a named enum constant as suggested in @R..'s answer.
a
不是常量表达式。它是一个 const 限定的变量。如果您想要一个可在常量表达式中使用的符号名称,则需要一个预处理器宏 (#define a 0
) 或一个枚举 (enum { a = 0 };)。
a
is not a constant expression. It's aconst
-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 };
).