Ive been playing with switch / case and was wondering if there is a way to use multiple variables
something like
switch (a, b c)
{
case 1, 2, 3:
//do something
return;
}
i know that code wont compile, but is there a proper syntax for something like that or is there a different tool?
1) you can nest switches
switch (a, b c)
{
case 1:
switch(b)
{
case 2:
etc
will result is a forest of code.
2) combine abc to one state (bit stuffing)
depending on the range of the values a,b,c you can pack these three vars in one .
suppose a = 0-3 (needs 2 bits) and b = 0-31 (5 bits) and c = 0-8, (3 bits)
then you can make
int val = a + b << 2 + c << 7 // val = [0000 00CC CBBB BBAA] bit pattern
and do the same for all relevant values.
As this is quite error prone you can "macrofy" this, see the sample sketch below (IDE 0.22)
//
// FILE: MultiSwitch.pde
// AUTHOR: Rob Tillaart
// DATE: 09-06-2012
//
// PUPROSE: macrofying a multiple switch
//
#define SWITCH(a,b,c) switch(a + b<<2 + c<<7)
#define CASE(a,b,c) case(a + b<<2 + c<<7)
void setup()
{
Serial.begin(9600);
Serial.println("start...");
}
void loop()
{
int a=2, b=3, c=4;
int x = 5;
SWITCH(a,b,c)
{
CASE(1,2,3):
x=4;
break;
CASE(2,3,4):
x=3;
break;
default:
x=6;
break;
}
Serial.println(x);
delay(500);
a=1, b=2, c=3;
SWITCH(a,b,c)
{
CASE(1,2,3):
x=4;
break;
CASE(2,3,4):
x=3;
break;
default:
x=6;
break;
}
Serial.println(x);
delay(500);
a++;
SWITCH(a,b,c)
{
CASE(1,2,3):
x=4;
break;
CASE(2,3,4):
x=3;
break;
default:
x=6;
break;
}
Serial.println(x);
delay(500);
}
notes:
- all warnings about using macros apply,
- there are limitations how long the bitpattern can be => use a long for var a to maximise the trick.
- multiple multicase switches need additional macros