4.3. if Selection Statement
Programs use selection statements to
choose among alternative courses of action. For example, suppose the passing
grade on an exam is 60. The statement
if ( grade >= 60 )
cout << "Passed";
determines whether the condition
grade >= 60 is true or false. If it is
true, "Passed" is printed and the next
statement in order is performed. If the condition is false, the printing is ignored and the next statement in order
is performed. Note that the second line of this selection statement is indented.
Such indentation is optional, but recommended.
Figure 4.3 illustrates the
single-selection if statement. It contains
what is perhaps the most important symbol in an activity diagram—the diamond or
decision symbol, which indicates that a decision is to be made. A
decision symbol indicates that the workflow will continue along a path
determined by the symbol's associated guard
conditions, which can be true or false. Each
transition arrow emerging from a decision symbol has a guard condition
(specified in square brackets above or next to the transition arrow). If a
particular guard condition is true, the workflow enters the action state to
which that transition arrow points. In Fig. 4.3,
if the grade is greater than or equal to 60, the program prints "Passed" to the
screen, then transitions to the final state of this activity. If the grade is
less than 60, the program immediately transitions to the final state without
displaying a message.

In C++, a decision can be based on
any expression—if the expression evaluates to zero, it is treated as false; if
the expression evaluates to nonzero, it is treated as true. C++ provides the
data type bool for variables that can hold only the values true and false—each of these is
a C++ keyword.
Portability Tip 4.1
|
For
compatibility with earlier versions of C, which used integers for Boolean
values, the bool value true also
can be represented by any nonzero value (compilers typically use 1) and the
bool value false also can be
represented as the value
zero. |