if (expression1)
{
statement1a;
statement1b;
}
else if(expression2)
{
statement2a;
statement2b;
}
else
{
statement3a;
statement3b;
}
In this case, each expression will be evaluated
sequentially looking for the first non-zero (true) expression
and if they all equal 0 (false), we do the final block of
statements. You can omit the final else statement if you
want to do nothing if all the expressions are 0 (false).
Note also that only the first true expression is used; if
expression1 is true and expression2 is also true, it won't
matter because the code will exit the if-else after the first
true case. We could use this construction to write a block
of code for interpreting joystick input positions:
if(input == KEY_UP) keyUP();
else if(input == KEY_DOWN) keyDOWN();
else if(input == KEY_LEFT) keyLEFT();
else if(input == KEY_RIGHT) keyRIGHT();
else if(input == KEY_PUSH) keyPUSH();
else keyERROR();
This says: If the input is equal to KEY_UP, then call
the keyUP() function. If the first line is true, then the rest of
the statements are skipped. If the first line isn't true, then
each line is evaluated sequentially until a true expression
is found or it calls the final 'else' keyError() function.
Switch
The 'if else' construction limits us to expressions that
are either true or false. If we want to make decisions using
expressions that can have any numeric result, we use the
switch statement that selects an expression with results
equal to a specified constant.
We can redo the if-else block used in the joystick
interrupt example using a switch statement as follows:
switch(input){
case KEY_UP:
keyUP();
break;
case KEY_DOWN:
keyDOWN();
break;
SMILEY’S WORKSHOP ☺
case KEY_LEFT:
keyLEFT();
break;
case KEY_RIGHT:
keyRIGHT();
break;
case KEY_PUSH:
keyPUSH();
break;
default:
keyERROR();
break;
}
This works just like the if-else block. The 'break'
statement causes an immediate exit from the switch block
— there is no need to check the rest as we have found
our case. If you want to continue evaluating cases against
the input, leave out the break and the next statements will
be looked at. You can let cases fall through, which can be
handy in circumstances such as evaluating character input
where you don't care if the character is a capital or lower
case letter, or perhaps you want the same response for a
range of integers:
switch(input){
case 'a' :
case 'A' :
doaA();
break;
case 'b' :
case 'B' :
dobB();
break;
case '0' :
case '1' :
case '2' :
case '3' :
gofer0123();
break;
case '4' :
case '5' :
case '6' :
case '7' :
gofer4567();
break;
default:
doDefault();
break;
}
Switch statements are error prone and a frequent
source of head boinking bugs (one where you boink
your head for being dumb enough to leave out a break
statement). The break after default: isn't even necessary,
but is recommended (by K&R) as a good practice to
help you remember to use it when you add a statement
January 2009 81