简体   繁体   中英

is it possible to do an OR in a case statement?

I want to do something like:

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

Is this legal in C?

The variable that I am doing a switch on is an enumerated list data struct.

You can rely on the fact that case statements will fall-through without a break :

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

You can also use this in a more complicated case, where both values require shared work, but one (or more) of them additionally requires specific work:

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

Yes, you can simply skip the break in the first case to achieve the fall-through effect:

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

Many programmers get into the trap of fall-through inadvertently by forgetting to insert the break . This caused me some headaches in the past, especially in situations when I did not have access to a debugger.

you need:

case someenumvalue:
case someotherenumvalue :
    do some stuff
    break;

You can use fallthrough to get that effect:

case someenumvalue:
case someotherenumvalue :
    do some stuff
    break;

A case statement like a goto -- your program will execute everything after it (including other case statements) until you get to the end of the switch block or a break .

As others have specificied, yes you can logically OR things together by using a fall through:

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

But to directly answer your question, yes you can do a logical, or bit-wise or on them as well (it's just a case for the result of the operation), just be careful that you're getting what you'd expect:

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

If you choose to do the second implementation keep in mind that since you're || 'ing things, you'll either get a 1 or 0, and that's it, as the case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM