【问题标题】:is it possible to do an OR in a case statement?是否可以在案例陈述中进行 OR?
【发布时间】:2012-09-28 18:16:10
【问题描述】:

我想做这样的事情:

case someenumvalue || someotherenumvalue:
    // do some stuff
    break;

这在 C 中合法吗?

我正在打开的变量是一个枚举列表数据结构。

【问题讨论】:

标签: c syntax switch-statement


【解决方案1】:

您可以相信case 语句将失败而没有break

case SOME_ENUM_VALUE:  // fall-through
case SOME_OTHER_ENUM_VALUE:
    doSomeStuff();
    break;

您也可以在更复杂的情况下使用它,其中两个值都需要共享工作,但其中一个(或多个)还需要特定工作:

case SOME_ENUM_VALUE:
    doSpecificStuff();
    // fall-through to shared code
case SOME_OTHER_ENUM_VALUE:
    doStuffForBothValues();
    break;

【讨论】:

    【解决方案2】:

    是的,你可以直接跳过第一个case中的break来达到穿透效果:

    switch (expr) {
        case someenumvalue: // no "break" here means fall-through semantic
        case someotherenumvalue:
            // do some stuff
            break;
        default:
            // do some other stuff
            break;
    }
    

    许多程序员因忘记插入break 而无意中掉入了陷阱。过去这让我有些头疼,尤其是在我无法访问调试器的情况下。

    【讨论】:

      【解决方案3】:

      你需要:

      case someenumvalue:
      case someotherenumvalue :
          do some stuff
          break;
      

      【讨论】:

        【解决方案4】:

        您可以使用fallthrough 来获得该效果:

        case someenumvalue:
        case someotherenumvalue :
            do some stuff
            break;
        

        case 语句类似于goto - 您的程序将执行它之后的所有内容(包括其他case 语句),直到您到达switch 块或break 的末尾。

        【讨论】:

          【解决方案5】:

          正如其他人所指定的,是的,您可以通过使用跌落来逻辑地 OR 事物:

          case someenumvalue:         //case somenumvalue 
          case someotherenumvalue :   //or case someothernumvalue
             do some stuff
             break; 
          

          但是要直接回答您的问题,是的,您也可以对它们执行逻辑或按位or(这只是操作结果的一个案例),请注意您得到了什么你会期望:

          enum
          {
            somenumvalue1 = 0,
            somenumvalue2 = 1,
            somenumvalue3 = 2
          };
          
          int main()
          {
            int val = somenumvalue2; //this is 1
            switch(val) {
               case somenumvalue1: //the case for 0
                    printf("1 %d\n", mval);
                    break;
               case somenumvalue2 || somenumvalue3: //the case for (1||2) == (1), NOT the
                    printf("2 %d\n", mval);         //case for "1" or "2"
                    break;
               case somenumvalue3:     //the case for 2 
                    printf("3 %d\n", mval);
                    break;
            }
            return 0;
          }
          

          如果您选择执行第二个实现,请记住,既然您是 ||'ing 事物,您将得到 1 或 0,仅此而已。

          【讨论】:

            猜你喜欢
            • 2012-08-11
            • 1970-01-01
            • 2012-03-08
            • 1970-01-01
            • 1970-01-01
            • 2023-04-10
            • 2010-10-30
            • 2016-05-13
            • 2016-02-21
            相关资源
            最近更新 更多