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
Statement
switch
.
If we write the example above using the
switch
it would look like:
switch(optio ) {
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
statement
switch
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.