【问题标题】:Using enum type in a switch statement在 switch 语句中使用枚举类型
【发布时间】:2013-03-06 02:03:13
【问题描述】:

如果检测到某些特殊情况,我将使用 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;

}

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

如何让 switch 语句在这里正常工作?谢谢!

【问题讨论】:

    标签: c enums switch-statement


    【解决方案1】:

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

    【讨论】:

    • !!我应该看到的,但我没有。令人惊奇的是,您可以立即阅读而不会注意到。
    • 哦。我的。上帝。我已经习惯了 Verilog,我忘记了这一切。这个 C 代码是对我的一些 Verilog 项目的功能模拟。
    【解决方案2】:

    您没有使用关键字“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;
    
    }
    

    【讨论】:

      【解决方案3】:

      你错过了最重要的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;
      }
      

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-01-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-30
        • 1970-01-01
        • 2012-02-22
        • 2017-12-13
        相关资源
        最近更新 更多