Go Down

Topic: switch case - multiple outputs with same option (Read 4086 times) previous topic - next topic

GreyArea

Hi all

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

Code: [Select]

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

Code: [Select]
case 1,2:

or similar?

PaulS

Quote
Is there a way to enter multiple outputs for a single case
The Arduino supports a range option:
Code: [Select]
   case 1...2:

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

groundFungus

#2
Dec 19, 2017, 02:24 pm Last Edit: Dec 19, 2017, 02:25 pm by groundFungus
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?).

Code: [Select]
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.
You will save everyone's time if you read and follow the forum guidelines.  https://forum.arduino.cc/index.php/topic,148850.0.html

gfvalvo

#3
Dec 19, 2017, 02:24 pm Last Edit: Dec 19, 2017, 04:11 pm by gfvalvo
But, multiple case statements can execute the same code:
Code: [Select]
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;
  }
No technical questions via PM. They will be ignored. Post your questions in the forum so that all may learn.

econjack

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

groundFungus

Quote
The only way that I know is to set a range of values
And now I know a new way,  Thanks, gfvalvo.
You will save everyone's time if you read and follow the forum guidelines.  https://forum.arduino.cc/index.php/topic,148850.0.html

GreyArea

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

PaulS

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

Go Up