if
…else
Double-Selection StatementThe if
single-selection statement performs an indicated action only when the condition is true; otherwise, the action is skipped. The if
…else
double-selection statement allows you to specify an action to perform when the condition is true and another action when the condition is false. For example, the pseudocode statement
If student’s grade is greater than or equal to 60
Print “Passed”
Else
Print “Failed”
represents an if
…else
statement that prints “Passed” if the student’s grade is greater than or equal to 60, but prints “Failed” if it’s less than 60. In either case, after printing occurs, the next pseudocode statement in sequence is “performed.”
The preceding If…Else pseudocode statement can be written in C++ as
if (grade >= 60) {
cout << "Passed";
}
else {
cout << "Failed";
}
The body of the else
is also indented. Whatever indentation convention you choose should be applied consistently throughout your programs.
Indent both body statements (or groups of statements) of an if
…else
statement. Many IDEs do this for you.
If there are several levels of indentation, each level should be indented the same additional amount of space. We prefer three-space indents.
if
… else
StatementFigure 4.5 illustrates the flow of control in the preceding if
…else
statement. Once again, the symbols in the UML activity diagram (besides the initial state, transition arrows and final state) represent action states and decisions.
if
…else
StatementsA program can test multiple cases by placing if
…else
statements inside other if
…else
statements to create nested if
…else
statements. For example, the following pseudocode represents a nested if
…else
that prints A
for exam grades greater than or equal to 90, B
for grades 80 to 89, C
for grades 70 to 79, D
for grades 60 to 69 and F
for all other grades:
If student’s grade is greater than or equal to 90
Print “A”
else
If student’s grade is greater than or equal to 80
Print “B”
else
If student’s grade is greater than or equal to 70
Print “C”
else
If student’s grade is greater than or equal to 60
Print “D”
else
Print “F”
We use shading to highlight the nesting. This pseudocode may be written in C++ as
if (studentGrade >= 90) {
cout << "A";
}
else {
if (studentGrade >= 80) {
cout << "B";
}
else {
if (studentGrade >= 70) {
cout << "C";
}
else {
if (studentGrade >= 60) {
cout << "D";
}
else {
cout << "F";
}
}
}
}
If variable studentGrade
is greater than or equal to 90, the first four conditions in the nested if
…else
statement will be true, but only the statement in the if
part of the first if
…else
statement will execute. After that statement executes, the else
part of the “outermost” if
…else
statement is skipped. Many programmers prefer to write the preceding nested if
…else
statement in the following form, which is identical except for the spacing and intentation that the compiler ignores:
if (studentGrade >= 90) {
cout << "A";
}
else if (studentGrade >= 80) {
cout << "B";
}
else if (studentGrade >= 70) {
cout << "C";
}
else if (studentGrade >= 60) {
cout << "D";
}
else {
cout << "F";
}
The latter form avoids deep indentation of the code to the right. Such indentation often leaves little room on a line of code, forcing lines to wrap.
In a nested if
…else
statement, ensure that you test for all possible cases.
else
ProblemThroughout the text, we always enclose control statement bodies in braces ({
and }
). This avoids a logic error called the “dangling-else
” problem. We investigate this problem in Exercises 4.23–4.25.
The if
statement normally expects only one statement in its body. To include several statements in the body of an if
(or the body of an else
for an if
…else
statement), enclose the statements in braces. As we’ve done throughout the text, it’s good practice to always use the braces. Statements contained in a pair of braces (such as the body of a control statement or function) form a block. A block can be placed anywhere in a function that a single statement can be placed.
The following example includes a block of multiple statements in the else
part of an if
…else
statement:
if (grade >= 60) {
cout << "Passed";
}
else
{
cout << "Failed
";
cout << "You must take this course again.";
}
In this case, if grade
is less than 60, the program executes both statements in the body of the else
and prints
Failed
You must take this course again.
Without the braces surrounding the two statements in the else
clause, the statement
cout << "You must take this course again.";
would be outside the body of the else
part of the if
…else
statement and would execute regardless of whether the grade was less than 60.
Syntax errors (such as when one brace in a block is left out of the program) are caught by the compiler. A logic error (such as an incorrect calculation) has its effect at execution time. A fatal logic error causes a program to fail and terminate prematurely. A nonfatal logic error allows a program to continue executing but causes it to produce incorrect results.
Just as a block can be placed anywhere a single statement can be placed, it’s also possible to have an empty statement, which is represented by placing a semicolon (;
) where a statement would normally be.
Placing a semicolon after the parenthesized condition in an if
or if
…else
statement leads to a logic error in single-selection if
statements and a syntax error in double-selection if
…else
statements (when the if
-part contains a body statement).
?:
)C++ provides the conditional operator (?:
) that can be used in place of an if
…else
statement. This can make your code shorter and clearer. The conditional operator is C++’s only ternary operator (i.e., an operator that takes three operands). Together, the operands and the ?:
symbol form a conditional expression. For example, the statement
cout << (studentGrade >= 60 ? "Passed" : "Failed");
prints the value of the conditional expression. The first operand (to the left of the ?
) is a condition, the second operand (between the ?
and :
) is the value of the conditional expression if the condition is true and the third operand (to the right of the :
) is the value of the conditional expression if the condition is false. The conditional expression in this statement evaluates to the string "Passed"
if the condition
studentGrade >= 60
is true and to the string "Failed"
if it’s false. Thus, this statement with the conditional operator performs essentially the same function as the first if
…else
statement in Section 4.6. The precedence of the conditional operator is low, so the entire conditional expression is normally placed in parentheses. We’ll see that conditional expressions can be used in some situations where if
…else
statements cannot.
The values in a conditional expression also can be actions to execute. For example, the following conditional expression also prints "Passed"
or "Failed"
:
grade >= 60 ? cout << "Passed" : cout << "Failed";
The preceding is read, “If grade
is greater than or equal to 60
, then cout << "Passed"
; otherwise, cout << "Failed"
.” This is comparable to an if
…else
statement. Conditional expressions can appear in some program locations where if
…else
statements cannot.