C语言 在 switch 语句中使用枚举类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15237656/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 05:35:00  来源:igfitidea点击:

Using enum type in a switch statement

cenumsswitch-statement

提问by tomocafe

I am using a switch statement to return from my main function early if some special case is detected. The special cases are encoded using an enum type, as shown below.

如果检测到某些特殊情况,我将使用 switch 语句尽早从主函数返回。特殊情况使用枚举类型进行编码,如下所示。

typedef enum {
    NEG_INF,
    ZERO,
    POS_INF,
    NOT_SPECIAL
} extrema;

int main(){

    // ...

    extrema check = POS_INF;

    switch(check){
        NEG_INF: printf("neg inf"); return 1;
        ZERO: printf("zero"); return 2;
        POS_INF: printf("pos inf"); return 3;
        default: printf("not special"); break;
    }

    // ...

    return 0;

}

Strangely enough, when I run this, the string not specialis printed to the console and the rest of the main function carries on with execution.

奇怪的是,当我运行它时,字符串not special被打印到控制台,而主函数的其余部分继续执行。

How can I get the switch statement to function properly here? Thanks!

我怎样才能让 switch 语句在这里正常运行?谢谢!

回答by ldav1s

No caselabels. You've got gotolabels now. Try:

没有case标签。你goto现在有标签了。尝试:

switch(check){
    case NEG_INF: printf("neg inf"); return 1;
    case ZERO: printf("zero"); return 2;
    case POS_INF: printf("pos inf"); return 3;
    default: printf("not special"); break;
}

回答by Jonathan Leffler

You're missing the all-important case:

你错过了最重要的case

switch(check){
    case NEG_INF: printf("neg inf");     return 1;
    case ZERO:    printf("zero");        return 2;
    case POS_INF: printf("pos inf");     return 3;
    default:      printf("not special"); break;
}

You created some (unused) labels with the same names as your enumeration constants (which is why it compiled).

您创建了一些与枚举常量同名的(未使用的)标签(这就是编译的原因)。

回答by Deepu

You haven't used the keyword "case". The version given below will work fine.

您还没有使用关键字“case”。下面给出的版本将正常工作。

typedef enum {
    NEG_INF,
    ZERO,
    POS_INF,
    NOT_SPECIAL

} extrema;

int main(){

    extrema check = POS_INF;

    switch(check){
        case NEG_INF: printf("neg inf"); return 1;
        case ZERO: printf("zero"); return 2;
        case POS_INF: printf("pos inf"); return 3;
        default: printf("not special"); break;
    }

    return 0;

}