三种颜色的英文单词已经用数字赋值了,为什么还报错了


#include<stdio.h>
const int red=0;
const int yellow=1;
const int green=2;
int main()
{
    int color;
    char *colorName=NULL;
    scanf("%d",&color);
    switch(color)
    {
        case red:colorName="red";break;
        case yellow:colorName="yellow";break;
        case green:colorName="green";break;
        default :colorName="unknown";break;
    }
    printf("%s",colorName);
    return 0;
}

img

不能这样用。在C中,所有 case 标签都必须是编译时常量。 在 C 中,const 限定符不会创建编译时常量,它只是指定运行时变量是只读的。
可以用枚举类型定义:

#include<stdio.h>

enum COLOR
{
      RED=0, YELLOW, GREEN
};

int main()
{
    int color;
    char *colorName=NULL;
    scanf("%d",&color);
    switch(color)
    {
        case RED:colorName="red";break;
        case YELLOW:colorName="yellow";break;
        case GREEN:colorName="green";break;
        default :colorName="unknown";break;
    }
    printf("%s",colorName);
    return 0;
}

const修饰的还是一个变量,在switch case中是不能够使用变量的。所以会报错。可以尝试这样写写是否能够正常编译运行 case 1

这么改下:
#define red 0 //const int red=0;
#define yellow 1 //const int yellow=1;
#define green 2 //const int green=2;