我想在新常量的定义中使用一些先前定义的常量,但我的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
Run Code Online (Sandbox Code Playgroud)
有没有办法使用其他常量的值来定义常量?如果没有,这种行为的原因是什么?
Const变量不能定义为表达式.
#define A (1)
#define B (2)
#define C (A + B)
const int a = A;
const int b = B;
const int c = C;
Run Code Online (Sandbox Code Playgroud)
使用枚举优先于预处理器宏来获取整数const值:
enum {
A = 1,
B = 2
};
const int a = A;
const int b = B;
const int c = A;
const int sum = (A + B);
Run Code Online (Sandbox Code Playgroud)
适用于C和C++.