Monday, May 16, 2011

When is a switch statement better than multiple if statements?


A switch statement is generally best to use when you have more than two conditional expressions based on
a single variable of numeric type. For instance, rather than the code
if (x == 1)
printf(“x is equal to one.\n”);
else if (x == 2)
printf(“x is equal to two.\n”);
else if (x == 3)
printf(“x is equal to three.\n”);
else
printf(“x is not equal to one, two, or three.\n”);
the following code is easier to read and maintain:
switch (x)
{
case 1: printf(“x is equal to one.\n”); break;
case 2: printf(“x is equal to two.\n”);
break;
case 3: printf(“x is equal to three.\n”);
break;
default: printf(“x is not equal to one, two, or three.\n”);
break;
}
Notice that for this method to work, the conditional expression must be based on a variable of numeric type
in order to use the switch statement. Also, the conditional expression must be based on a single variable. For
instance, even though the following if statement contains more than two conditions, it is not a candidate
for using a switch statement because it is based on string comparisons and not numeric comparisons:
char* name = “Lupto”;
if (!stricmp(name, “Isaac”))
printf(“Your name means ‘Laughter’.\n”);
else if (!stricmp(name, “Amy”))
printf(“Your name means ‘Beloved’.\n “);
else if (!stricmp(name, “Lloyd”))
printf(“Your name means ‘Mysterious’.\n “);
else
printf(“I haven’t a clue as to what your name means.\n”);