switch case - multiple outputs with same option

Hi all

Just a quick one. If I use a switch...case statement on a variable called "test";

switch (test){
case 1:
//do thing 1
break;
case 2:
//do thing 2
break;
case 3:
//do thing 2
break;
}

as you'll see the result of test being either 2 or 3 results in the same action. Is there a way to enter multiple outputs for a single case, eg

case 1,2:

or similar?

Is there a way to enter multiple outputs for a single case

The Arduino supports a range option:

   case 1...2:

There is NO way to have one case statement handle discrete values that are not consecutive (i.e. 3 and 7).

No, not that way. The only way that I know is to set a range of values in the case using ellipses.

This will trigger the case on either 2 or 3. But the range must be inclusive (contiguous?).

int test = 3;

void setup()
{
  Serial.begin(115200);
  switch (test)
  {
    case 1:
      Serial.println("thing 1");
      break;
    case 2 ... 3:  
      Serial.println("thing 2");
      break;   
  }
}

void loop() 
{
}

Paul beat me too it, but I will post my example.

But, multiple case statements can execute the same code:

switch (test) {
    case 1:
      //do thing 1
      break;

    case 2:
    case 3:
    case 13:
    case 99:
      //do thing 2
      break;

    case 11:
    case 21:
      // do thing 3
      break;

    default:
      break;
  }
4 Likes

I kinda like the fall-through option gfvalvo shows because you can add comments about each case if you wish.

1 Like

The only way that I know is to set a range of values

And now I know a new way, Thanks, gfvalvo.

Hmm...does the fall through option have to be in numerical order?

does the fall through option have to be in numerical order?

No.