# Can i use a switch case for two variables

I’m currently working on a project (Object following robot) and was wondering if its possible to use switch case with two variables (Ultrasonic Sensors) I am currently using if else but its not going well. Maybe someone out there could throw me some pointers or tell me what I am doing wrong. I’m new to the forum and hope i have put this in the right place. Thanks in advance.

A_Setup.ino (788 Bytes)

B_Loop.ino (2.17 KB)

Capstone_V2.0.ino (1.53 KB)

use switch case with two variables (Ultrasonic Sensors)

No. A switch statement lets you choose one case based on one value.

tell me what I am doing wrong.

You posted some code, but did not tell us what it does, or how that differs from what you want.

PaulS: No. A switch statement lets you choose one case based on one value.

Well, you could use a fall through and have several cases based on certain values...

``````switch(value)
{
case a:
functionA();
case b:
functionB();
case c:
functionC();
break;
default:
break;
}
``````

You can combine two variables into a single new variable, and use that in the switch. For example, if you have two variables, one that can have values 0, 1 or 2, and the other can have the values 3,4 or 5, you can combine them:

``````int thing1;  // Can have values 0, 1 or 2
int thing2;  // Can have values 3, 4 or 5

...

int switchvar = (thing1 * 10) | thing2;
switch (switchvar)
{
case 3:    // thing1==0, thing2==3
break;
case 13:    // thing1==1, thing2==3
break;
case 23:    // thing1==2, thing2==3
break;
case 4:    // thing1==0, thing2==4
break;
case 14:    // thing1==1, thing2==4
break;
case 24:    // thing1==2, thing2==4
break;
case 5:    // thing1==0, thing2==5
break;
case 15:    // thing1==1, thing2==5
break;
case 25:    // thing1==2, thing2==5
break;
}
``````

Regards, Ray L.