Is it possible to do OR in case?

I want to do something like:

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

Is this legal in C?

The variable that I run is an enumerated data structure of the list.

+4
source share
5 answers

You can rely on case to fail without break :

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

You can also use this in the more complicated case, when both values โ€‹โ€‹require collaboration, but one (or more) of them additionally requires some work:

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

Yes, you can just skip break in the first case to achieve the fall 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 accidentally fall into the trap of failure, forgetting to insert break . This caused me some headaches in the past, especially in situations where I did not have access to the debugger.

+2
source

you need:

 case someenumvalue: case someotherenumvalue : do some stuff break; 
+2
source

You can use walkthrough to get this effect:

 case someenumvalue: case someotherenumvalue : do some stuff break; 

A case , like a goto - your program will execute everything behind it (including other case ) until you reach the end of the switch or break block.

+1
source

As others have specified, yes, you can logically OR things together using failure:

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

But for a direct answer to your question, yes, you can make logical or bit-wise or on them (this is just a case for the result of the operation), just be careful that you get what you 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 decide to make a second implementation, keep in mind that since you || 'things, you either get 1 or 0, and thatโ€™s like a case.

+1
source

Source: https://habr.com/ru/post/1436870/


All Articles