const static int 数组

Array of const static int

我在 header 中有变量:

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};

但是编译器说错误:

initializer element is not constant

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

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

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

All the expressions in an initializer for an object that has static or thread storage duration shall be constant expressions or string literals.

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

你可以做的是定义它们,所以这些值在编译时是常量:

#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);
}