if
if - else
statements like this:
if( option == 1 ) ... else if( option == 2 ) ... else if( option == 3 ) ... . . . else ...
Notice that even though the later if
statements
are in the else
clause of the first if
statement, we don't indent these false branches.
Instead we think of the else if
as an idiom
that is like its own keyword.
Thus we recognize this structure as a multi-way decision.
switch
Statementswitch
.
If we write the example above using the switch
it would look like:
switch( option ) { case 1: ... break ; case 2: ... break ; case 3: ... break ; . . . default: ... break ; }
switch
like this:
switch( option ) { case 'a': case 'A': ... break ; case 'b': case 'B': ... break ; case 'c': case 'C': ... break ; . . . default: ... break ; }
'a'
or an 'A'
(that is a lower or uppercase a),
then we'll do that first block of code.
break
statementswitch
that we
haven't seen before, the break
statement.
In the context of a switch
, it transfers control
to the bottom of the switch
statement.
(We'll see later that it does the
same thing with looping statements.)
Without the break
statement, flow would
"fall through" into the next case.
For example, if a = 5
switch( a ) { case 5: x = y ; case 6: x = z ; break ; }
x
will end up being equal to z
just as if a
had been 6.
x
at the end of this switch statement?
x = 10 ; switch( x ) { case 1: case 2: x++ ; break ; case 8: case 9: case 10: case 11: x-- ; case 13: x *= 2 ; break ; default: x = 0 ; }