c - const static int 数组

标签 c arrays compiler-errors initialization constants

我在标题中有变量:

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

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

最佳答案

您可以做的就是定义它们,以便这些值在编译时保持不变:

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

关于c - const static int 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31313459/

相关文章:

c++ - 使用 Visual Studio 但有/没有 .NET 的 C/C++ GUI 应用程序

c - printf ("%u\n",4294967296) 在 ubuntu 服务器 11.10 for i386 上输出 0 并带有警告

javascript - 如何在 for 循环中对具有精确索引的元素重复迭代?

c++ - 在类成员的实例化期间: "no operator "[ ]"matches these operands"使用 map[key] 访问 std::map 值时

c - char * const 和 const char * 有什么区别?

c - 以下代码是否泄漏内存

javascript - 从数组创建动态对象树

c++ - 分配数组时 operator new 的问题

java - 如果发现预期的EOF

C函数调用奇怪错误