Is there a way to use const variables in the definitions of other constants?

Is there a way to use const variables in the definitions of other constants?

因为看清所以看轻 发布于 2021-11-26 字数 461 浏览 919 回复 4 原文

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

岁月无声 2022-06-07 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 };
南汐寒笙箫 2022-06-07 3 楼

You can only assign a literal to a const variable, so that program is illegal.
I think you should go with the preprocessor.

倒数 2022-06-07 2 楼

Use enums in preference to preprocessor macros for integral const values:

enum {
    A = 1,
    B = 2
};

const int a = A;
const int b = B;
const int c = A;        
const int sum = (A + B);

Works in C and C++.

晨曦慕雪 2022-06-07 1 楼

Const vars can't be defined as an expression.

#define A (1)
#define B (2)
#define C (A + B)

const int a = A;
const int b = B;
const int c = C;