asf2013 2021-09-21 12:50 采纳率: 66.7%
浏览 55
已结题

case后用常量代替int值为什么会报错?

#include <stdio.h>
int red = 0;
int yellow=1;
int green=2;

int main(int argc,char const *argv[])
{
    int color=-1;
    char *output=NULL;
    
    scanf("%d",&color);
    switch(color)
    {
        case red: output="red";break;
        case yellow: output="yellow";break;
        case green: output="green";break;
        default: output="unknown";
    }
    
    printf("%s\n",output);
    
    
    return 0;
}

这段代码在case处会报错[Error] case label does not reduce to an integer constant,但是red,yellow,green的值已经在之前定义为常量了,为什么会报错呢,求教。

  • 写回答

2条回答 默认 最新

  • joel_1993 2021-09-21 12:57
    关注

    定义#define 就行

    #include <stdio.h>
    #define red 0
    #define yellow 1
    #define green 2
    int main(int argc,char const *argv[])
    {
        int color=-1;
        char *output=NULL;
        scanf("%d",&color);
        switch(color)
        {
            case red: output="red";break;
            case yellow: output="yellow";break;
            case green: output="green";break;
            default: output="unknown";
        }
        printf("%s\n",output);
        
        return 0;
    }
     
     
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 9月29日
  • 已采纳回答 9月21日
  • 创建了问题 9月21日