Arduino Forum

Using Arduino => Programming Questions => Topic started by: GreyArea on Dec 19, 2017, 02:11 pm

Title: switch case - multiple outputs with same option
Post by: GreyArea on Dec 19, 2017, 02:11 pm
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?
Title: Re: switch case - multiple outputs with same option
Post by: PaulS on Dec 19, 2017, 02:16 pm
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).
Title: Re: switch case - multiple outputs with same option
Post by: groundFungus on Dec 19, 2017, 02:24 pm
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.
Title: Re: switch case - multiple outputs with same option
Post by: gfvalvo on Dec 19, 2017, 02:24 pm
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;
  }
Title: Re: switch case - multiple outputs with same option
Post by: econjack on Dec 19, 2017, 04:09 pm
I kinda like the fall-through option gfvalvo shows because you can add comments about each case if you wish.
Title: Re: switch case - multiple outputs with same option
Post by: groundFungus on Dec 19, 2017, 04:13 pm
Quote
The only way that I know is to set a range of values
And now I know a new way,  Thanks, gfvalvo.
Title: Re: switch case - multiple outputs with same option
Post by: GreyArea on Dec 19, 2017, 04:26 pm
Hmm...does the fall through option have to be in numerical order?
Title: Re: switch case - multiple outputs with same option
Post by: PaulS on Dec 19, 2017, 04:39 pm
Quote
does the fall through option have to be in numerical order?
No.