有没有办法在其他常量的定义中使用 const 变量?
我想在新常量的定义中使用一些先前定义的常量,但我的 C 编译器不喜欢它:
const int a = 1;
const int b = 2;
const int c = a; // error: initializer element is not constant
const int sum = (a + b); // error: initializer element is not constant
有没有办法使用其他常量的值来定义常量? 如果不是,这种行为的原因是什么?
I would like to use some previously defined constants in the definition of a new constant, but my C compiler doesn't like it:
const int a = 1;
const int b = 2;
const int c = a; // error: initializer element is not constant
const int sum = (a + b); // error: initializer element is not constant
Is there a way to define a constant using the values of other constants? If not, what is the reason for this behavior?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Const vars 不能定义为表达式。
Const vars can't be defined as an expression.
对于整数 const 值,优先使用枚举而不是预处理器宏:
适用于 C 和 C++。
Use enums in preference to preprocessor macros for integral const values:
Works in C and C++.
您只能将文字分配给 const 变量,因此该程序是非法的。
我认为你应该使用预处理器。
You can only assign a literal to a const variable, so that program is illegal.
I think you should go with the preprocessor.
由于结果是恒定的,我同意 Michael Burr 的观点,即枚举是实现这一点的方法,但除非您需要传递指向常量整数的指针,否则我不会使用“变量”(实际上是常量)变量?)但只是枚举:
Since the results are meant to be constant, I agree with Michael Burr that enums are the way to do it, but unless you need to pass pointers to constant integers around, I wouldn't use the 'variables' (is a constant really a variable?) but just the enums: