有没有办法在其他常量的定义中使用const变量?

e.J*_*mes 4 c constants

我想在新常量的定义中使用一些先前定义的常量,但我的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)

有没有办法使用其他常量的值来定义常量?如果没有,这种行为的原因是什么?

phi*_*llc 7

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)

  • #undef A #undef B #undef C. (6认同)

Mic*_*urr 7

使用枚举优先于预处理器宏来获取整数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++.

  • 不适用于C,仅适用于C++ - 但在这种情况下,您不需要'静态'只是以前看到的const int就足以使标识符可用作const(或数组大小)初始化程序的一部分. (2认同)