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:
Since switch
operates on a single variable, you'd have to be able to combine your multiple inputs into a single value somehow. Given the numerical values for the ASCII characters 'R', 'P', and 'S', adding the two characters together would give you a unique sum for each pairing. However, the resulting code would likely be more difficult to read than the equivalent if
tree. In general, this usually isn't a good option because your code will very easily break when new input options are added and the underlying assumptions for your "combination" operation (such as a unique sum) no longer hold. switch
also becomes unwieldy as the number of possible input values increases. Since you need a case
for every possible combination, your switch
would become large and difficult to maintain when used with anything more than a handful of input options.
A switch
block will actually result in more code than using if
for this particular case. Using if
gives you the ability to handle multiple cases at once. For example, you don't need three separate versions of the code that checks for a tie. You can also use a table to look up answers instead of switch
or if
. Here's an example that combines these approaches:
// Table of outcomes. The option in the second
// column wins over the option in the first column.
char matchup[3][2] = {
{'P', 'S'}, // paper is cut and destroyed
{'S', 'R'}, // scissors are smashed and destroyed
{'R', 'P'}, // rock is ... covered up?
};
void announce_winner(char player1, char player2)
{
int i;
if (player1 == player2) {
printf("Draw\n");
return;
}
for (i=0; i<3; ++i) {
if (player1 == matchup[i][0])
printf("%c wins\n", (player2 == matchup[i][1]) ? player2 : player1);
}
}
The big benefit of the table approach is that your code is separate from your data. If the rules of the game change or if someone is learning the game and wants to find out who wins in what situation, a table becomes much more user-friendly than having to dig through a lot of code. A switch
block is essentially the lookup table and the handling code all mixed together and for complex cases, it gets ugly fast.