Choosing Code with Selection Statements - C++

Often, people base their decisions on certain conditions. For example, a person might go to a doctor if he or she feels sick. The decision, whether to go the doctor, is based on a certain condition: feeling sick. The same is true when using programs. You can design your program so that it selects which code to execute based on certain conditions.

As you have learned, conditions in C++ have two possible values, true or false. The operators and operands that make up the condition determine a condition’s value.

There are two types of selection statements: if else statements and switch statements.

Testing Conditions with if Statements

Probably the most important selection statement is the if statement. The idea behind the if statement is that a special section of code contained within the statement (called the controlled statement) will be executed only if a certain condition (called the controlling condition, or just the condition) holds true. The general syntax for the if statement is

Here condition is the condition being tested, and controlledStatements is zero or more controlled statements. These controlled statements are executed only if condition evaluates to true. Note that there is no semicolon after condition. The entire two lines of this general syntax are one statement, so a semicolon is not required. Also, note that condition is in parentheses to separate it from the rest of the statement. These parentheses are required. If controlledStatements consists of only one statement, the syntax is this:

Here thestatement is the single statement. Note the semicolon at the end, telling the compiler that this is the entire if statement. When controlledStatements consists of more than one statement, the syntax looks like this:

Here statementList is zero or more C++ statements, each ending with a semicolon. Note that no semicolon is required at the end of the last curly brace ( } ). You might recall from Chapter 2 that a block of code is any section of code separated by curly braces. Blocks of code can be put anywhere a single statement is allowed. This is one example. Throughout this chapter, you will see quite a few examples of blocks of code. Keep an eye out for them.

It is possible to have zero statements in both forms of the syntax (note the semicolon in the first form and the lack of a semicolon in the second form):

The cout statement will never be executed because the condition (the controlling condition), swords < 8 (is the value of the integer variable swords less than 8?), evaluated to false. Nine is not less than eight. Because you want it to execute only one line of code, you can display this example in the alternate way—without the braces, as shown here:

In this example, because the braces are not used, the if statement consists of everything up to (and including) the semicolon. You can also create if statements without controlled statements, as shown in these two examples:

However, there is not a good reason to use an empty if statement because the statement doesn’t accomplish anything.

As we said earlier, the if statement is the most common control statement. When combined with the else if statements and else statements discussed next, the if statement can be one of your most powerful tools.

Including else if and else Statements

Sometimes you might want to take an alternative course of action if a certain condition does not hold true. Say, for example, that you feel sick. You might go to see a doctor; otherwise, you will stay home. The statement following the word otherwise is the alternative course of action. If the condition, feeling sick, is not true, you will take the alternative action, stay home.

In C++, the word otherwise is represented with the else statement. An else statement must always follow an if statement. An else statement cannot occur by itself. The syntax for an else statement is this:

Here controlledStatements is one or more statements. If you have more than one statement in controlled Statements, you must use a block, surrounded by curly braces, as shown here:

In the preceding, statementList consists of zero or more statements, separated by semicolons. If controlled Statements is zero or one statement, a block is not needed:

You connect an else statement with an if statement by putting the else statement right after the if statement:

The keyword else must immediately follow the if statement; if placed anywhere else, a compile error will occur.

Here’s an example:

Here, the text Swords is not less than 8 will display onscreen because the if statement’s condition is false; the else statement executes automatically. If the integer variable, swords, were initialized to 6, for example, the text Swords is less than 8 would display, and the entire else statement would be skipped.

It is possible for the statements controlled by an else statement to be composed of another if statement. This is how the infamous else if statement is formed. This is how it would look:

Here condition1 and condition2 are two separate conditions, and controlledStatements1 and controlledStatements2 are two separate sets of controlled statements. The preceding block of code executes as follows:

  • If condition1 is true, controlledStatements1 is executed and the computer skips the rest of the if, else if structure.
  • If condition1 is false and condition2 is true, the controlledStatements2 is executed, and the rest of the if, else if structure is skipped.
  • If condition1 and condition2 are both false, neither one of the controlled statements is executed.

Putting one if statement inside another if statement is called nesting if statements. See Figure for a diagram showing how the if, else if, else structure works.

This is how the if, else, if else structure works.

This is how the if, else, if else structure works.

The Three Tests of Honour Game

You are a brave knight standing in front of a labyrinth full of dark, cruel looking rooms. You must pass a number of tests that an evil wizard has set before you in order to rescue the damsel whom the evil wizard has kidnapped. If you manage to pass all these tests of honor, you and the damsel (in distress) will live happily ever after. The first room is a room full of gold. If you take any of the gold, you fail the test; however, you get to keep the gold you take. The second room is full of diamonds. If you take these, you will prove your greed and will not be able to rescue the damsel. In the last room, you must help rescue a peasant from a dragon. If you pass all three tests, the evil wizard will release the damsel.

Here is how this example looks using if and else statements:

As you can see in this example, the main part of the program starts with an if statement, which tests to see whether the player has chosen to take the gold or not. If the player takes the gold (by entering the number 1), the condition inside the parentheses evaluates to true (1 is equivalent to the value true), and the player can keep the gold. If the player keeps the gold, however, the player does not move on to the next test (and, therefore, the third test), the second room with the diamonds. In other words, if the first condition evaluates to true, the rest of the if, else structure is skipped.

On the other hand, if the player chooses not to take the gold, he or she passes the first test and moves on to the next room. If the player then chooses to take the diamonds, he or she can keep the diamonds, but in that case, the player will not have a chance to save the peasant or rescue the damsel. If one of the conditions holds true, the computer will execute the controlled statements that are controlled by the condition that held true. So, in this example, if the player takes the diamonds, the computer will execute the code that lets the player keep the diamonds and then it will skip to the end of the entire structure.

The third if statement is similar to the previous two. The player cannot rescue the peasant if he or she has taken the gold or diamonds. The line if (killedByDragons) is an example of one if statement. Notice that you do not need the braces around the statement. However, if you choose to place braces around the cout statement, the program will not change.

Last come the else statements. The else statements are default statements, which means that if the condition of the related if statement does not hold true, the code inside the else statement will be executed. That is, if the player did not take the gold or diamonds and defeated the dragon, the player—the brave knight—may marry the damsel and live happily ever after.

In the Real World
Do not underestimate if statements. They are one of the most important statements in the C++ language. The if statement is the basic structure from which the computer can decide what to do. if statements make your code nonlinear. Instead of following a basic start-to-finish path through the code, the computer can change the order in which things are executed to adapt to changing circumstances.

You will find many uses for if statements as you program. One example of when you can use if statements is in the creation of AI (artificial intelligence). Another more common example is when you are responding to user input in a computer game. If the user presses the right arrow, the user’s character should move to the right.

The Conditional Operator

Some conditions are very trivial, yet you still have to write a complete if statement for them. Observe the following:

This code snippet assigns the minimum of x and y to z. Writing a complete if, else statement for something so short can be tedious. Fortunately, C++ provides an alternative: the conditional operator. The preceding example is much more concise when you use this operator:

The general syntax for the conditional operator is as follows:

Here condition is a valid condition, and expr1 and expr2 are valid expressions. If condition is true, the conditional operator evaluates to expr1; otherwise, it evaluates to expr2. The conditional operator is an expression and can be used anywhere that other expressions can be used. You can see that this is similar to using an if statement. However, keep in mind that expr1 and expr2 are expressions and not statements (as are if statements). You cannot, for example, do the following:

Here is an example to illustrate the proper use of the conditional operator:

Using the switch Statement

The second type of selection statement is the switch statement. Many programmers try to avoid the switch statement, but if used correctly, it can be a powerful tool.

Imagine that you are programming a game that displays a menu with six choices. One way to respond is to use six if statements in a row. Even better, use an if, else if, else structure. The switch statement is an even simpler solution. It enables you to test one variable against certain values and respond differently to each one. Here is the general syntax for the switch statement:

Here expression, expr1, expr2, and expr3 are variables or expressions whose values you want to test. We discuss the break(opt.) lines shortly. This syntax is equivalent to an if, else if structure in meaning:

You can see how much more inconvenient an if, else if structure can be. When the switch statement executes, the computer goes through each case statement and tests whether expression equals exprN (where N is any number). If they are equal, everything after the case statement will be executed until the computer encounters the break keyword. If none of the tests evaluate to true, the whole switch statement does nothing.

The break keyword is new to you. It exits (causes the computer to go to the end of) the nearest enclosing switch statement or iteration statement. If the break keyword is not enclosed by a switch statement or iteration statement, a syntax error occurs when you try to compile. The line break(opt.) in the general syntax means that the break keyword is optional there. Shortly, you will learn the implications of leaving this word out, but for now, put it at the end in every case.

Now that you’ve made it through all the confusing definitions, it’s time for an example:

As you can see from the output, the computer chose the correct case statement and executed it. All the other case statements are ignored.

Note that a break statement isn’t required within every case statement (and sometimes it is useful not to have one). Observe the following example:

The default Case

You might not always be able to account for all possible values in a switch statement or you might sometimes want to perform the same action for many cases. C++ provides an else statement, called the default statement, that is part of the switch statement. The default statement is just like the case statement except that there is no value to test. The syntax for the default statement is as follows:

If the default statement is encountered, controlledStatements automatically executes. There is not a test for the default statement as there is for the case statement. You must place the default statement at the end of the list of case statements. Here is an example:

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd Protection Status

C++ Topics