【问题标题】:Array of const static int [duplicate]const static int数组[重复]
【发布时间】:2015-07-09 09:28:36
【问题描述】:

我在标题中有变量:

const static int RED = 0;
const static int BLUE = 1;
const static int GREEN = 5;
const static int DOG = 8;
const static int CAT = 9;
const static int SNAKE = 7;

如何创建一个全局数组并使用这些 const 变量的值对其进行初始化?

我试过了:

const static int color[3] = {BLUE, GREEN, DOG};
const static int animal[3] = {DOG, CAT, SNAKE};

但是编译器说错误:

初始化元素不是常量

(我需要创建一些可以循环的结构。)

【问题讨论】:

  • 为什么不使用枚举代替?
  • @JoachimPileborg 是否可以遍历不连续的枚举?

标签: c arrays compiler-errors initialization constants


【解决方案1】:

你可以做的是定义它们,所以值在编译时是恒定的

#define RED 0
#define BLUE 1
#define GREEN 5

const static int color[3] = {BLUE, GREEN, DOG};

或者您可以在运行时设置数组中的所有元素:

const static int color[3];
color[0] = BLUE;
color[1] = GREEN;
color[2] = DOG;

for(i = 0; i < 3; i++){ 
  if(color[i] == BLUE)
     printf("\nColor nr%d is blue", i);
}

【讨论】:

    【解决方案2】:

    C 中,使用const 不会使变量成为编译时间常数。它被称为const qualified. 因此,您不能使用const 变量在全局范围内初始化另一个变量。

    相关,来自C11,第 §6.7.9 章,初始化

    具有静态或线程存储持续时间的对象的初始化程序中的所有表达式 应该是常量表达式或字符串文字。

    因此,为了完成工作,您可以将 REDBLUE 设为 MACRO(使用 #define),或者将这些标识符名称用作枚举常量。

    【讨论】:

    • 很好的解释。顺便说一句,当我用 gcc(Apple LLVM 版本 6.1.0 (clang-602.0.53))测试代码时,编译器没有抱怨。它似乎是有线的。
    猜你喜欢
    • 2012-01-07
    • 2015-01-02
    • 1970-01-01
    • 2012-12-26
    • 1970-01-01
    • 2016-08-28
    • 1970-01-01
    • 2016-10-05
    • 1970-01-01
    相关资源
    最近更新 更多