I have an IF-statement that I want to transform into a Switch-statement... But it has 2 variables! Is it possible to do it on C?
It is a rock, paper, scissors game:
In general, the answer is "no": switch
statements work with a single variable. However, in some cases you can do the conversion. For example, if you have two variables, a
and b
, where a
can be 0, 1, or 2, and b
that can be 0, 1, 2, or 3
, you can do a switch like this:
switch (a*10+b) {
case 0: break; // a == 0, b == 0
case 10: break; // a == 1, b == 0
case 20: break; // a == 2, b == 0
case 1: break; // a == 0, b == 1
case 11: break; // a == 1, b == 1
case 21: break; // a == 2, b == 1
case 2: break; // a == 0, b == 2
case 12: break; // a == 1, b == 2
case 22: break; // a == 2, b == 2
case 3: break; // a == 0, b == 3
case 13: break; // a == 1, b == 3
case 23: break; // a == 2, b == 3
}