Is there a way to use const variables in the definitions of other constants?
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?
如果你对这篇文章有疑问,欢迎到本站 社区 发帖提问或使用手Q扫描下方二维码加群参与讨论,获取更多帮助。

评论(4)

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:
enum { a = 1 };
enum { b = 2 };
enum { c = a };
enum { sum = a + b };


发布评论
需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。