number += (number % 2 == 1 ) ? 1 : 0 ;
double discount; char code = 'B' ; switch ( code ) { case 'A': discount = 0.0; break; case 'B': discount = 0.1; break; case 'C': discount = 0.2; break; default: discount = 0.3; }
Often a program needs to make a choice among several options based on the value of a single expression. For example, a clothing store might offer a discount that depends on the quality of the goods:
The program fragment does that.
A choice is made between four options
based on the value in code
.
The switch
statement
looks at the case
s to find a
match for the value in code
.
It then executes the statement between the matching case
and the following break
.
All other case
s are skipped.
If there is no match, the "default" case is chosen.
Warning: the complete rules for switch
statements
are complicated.
Read on to get the details.
If code
is 'C', what is the
discount?