Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group multiple cases together in the switch statement

Tags:

c++

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.

like image 616
jingweimo Avatar asked Oct 20 '25 12:10

jingweimo


2 Answers

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*/
};
like image 152
PSkocik Avatar answered Oct 23 '25 02:10

PSkocik


Yes, this is absolutely fine, although I'd write

if (pin >= 2 && pin <= 35){
    dataOut[pin-2] = 1;
    DAQmxWriteDigitalLines( ...
}

if I were you. If you are using gcc exclusively as your compiler, then you could also use case ranges.

like image 32
Bathsheba Avatar answered Oct 23 '25 02:10

Bathsheba