Group multiple cases together in the switch statement

  • A+
Category:Languages

Here below is my code for a switch statement:

 switch(pin)   {   case 1:     break;   case 2:   case 3:  case 4:  case 5:  case 6:  case 7:  case 8:  case 9:  case 10:  case 11:   case 12:  case 13:  case 14:  case 15:  case 16:  case 17:  case 18:  case 19:  case 20:   case 21:  case 22:  case 23: case 24:case 25:case 26:case 27:case 28:case 29: case 30: case 31:   case 32: case 33: case 34: case 35:      dataOut[pin-2] = 1;     DAQmxWriteDigitalLines(taskHandleOut,1,1,10.0,DAQmx_Val_GroupByChannel,dataOut,NULL,NULL);      break;    default:     break; 

In the above, the case 2-35 are to be grouped together for which, I mean, when pin is equal to 2-35, the specific task is to be performed.

I want to know if the above code is valid or not. I haven't seen case grouping in switch statements. Any weblinks for similar multiple case grouping is appreciated. Maybe there is some better way to do so instead of grouping multiple cases.

 


While your case may be better served with an if-check if (pin >= 2 && pin <= 35), it is common to group case labels like that.

gcc/clang/tinycc even have syntactic sugar for it:

switch(pin){ case 2 ... 35: /*nonstandard GNU extension; note well the whitespace*/ }; 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: