The if Statement


The if statement is used to execute code only when the value of a relational expression is true. The syntax of an if statement is

 if (Boolean value)  statement; 

Both lines together are called an if statement. The first line consists of the if keyword followed by an expression, such as a relational expression, that evaluates to a Boolean value, true or false. The relational (or other Boolean) expression must be in parentheses, and should not be terminated with a semicolon.

The next line is called a conditional statement. As you may recall from Chapter 1, a statement is an instruction to the computer, directing it to perform a specific action. The statement is conditional because it executes only if the value of the relational expression is true. If the value of the relational expression is false, then the conditional statement is not executed ”meaning, it s essentially skipped .

The following program, which tests if a whole number entered by the user is even, illustrates the use of an if statement.

 #include <iostream> using namespace std; int main(void) {  int num;  cout << "Enter a whole number: ";  cin >> num;  if (num % 2 == 0)  cout << "The number is even" << endl;  return 0; } 

If the user enters an even number, then the program outputs that the number is even.

 Enter a whole number: 16 The number is even 

However, if the user enters an odd number, then there is no output that the number is even.

 Enter a whole number: 17 

Figure 5-3 is a flowchart of this program. This flowchart has one new symbol: a diamond. It s used to represent the true/false statement being tested .

click to expand
Figure 5-3: Flowchart of a program that determines whether a number is even

Let s now analyze how the program works. You may find the flowchart a helpful visual aid in following this textual explanation.

The program first prompts the user to enter a number. It then stores that input in the integer variable num.

The program next evaluates the relational expression num % 2 == 0, which is enclosed in parentheses following the if keyword. That expression involves two operators, the arithmetic modulus operator (%) and the relational equality operator (===). Since arithmetic operators have higher precedence than relational operators, the expression num % 2 will be evaluated first, with the result then compared to zero.

A number is even if, when divided by two, the remainder equals zero. You learned in Chapter 4 that the modulus operator will return the remainder from integer division. Accordingly, the expression num % 2 will divide the number entered by the user by two, and return the remainder. That remainder then will be compared to zero using the relational equality operator.

If the relational expression is true, which it would be if the number inputted by the user is even, then the conditional statement executes, outputting The number is even. If the relational expression is false, which it would be if the number inputted by the user is odd, then the conditional statement is skipped, and it will not execute.

Indenting

It is good practice to indent the conditional statement.

 if (num % 2 == 0); // don't put a semicolon here!  cout << "The number is even" << endl; 

While the compiler doesn t care whether you indent or not, indentation makes it easier for you, the programmer, to see that the statement is conditional.

Common Mistakes

During several years of teaching C++ in an introductory programming class, I have noticed several common mistakes in the writing of if statements. Some of these mistakes may result in compiler errors and therefore are easy to spot. However, other mistakes are harder to pick out since they do not cause an error, either at compile time or run-time, but instead give rise to illogical results.

Don t Put a Semicolon after the Relational Expression!

The first common mistake is to place a semicolon after the relational expression:

 if (num % 2 == 0); // don't put a semicolon here!  cout << "The number is even" << endl; 

Since the compiler generally ignores blank spaces, the following if statement would be the same, and better illustrates visually the problem:

 if (num % 2 == 0)  ; // don't put a semicolon here!  cout << "The number is even" << endl; 

No compiler error will result. The compiler will assume from the semicolon that it is an empty statement. An empty statement does nothing, and though it is perfectly legal in C++, and indeed sometimes has a purpose, here it is not intended.

One consequence will be that the empty statement will execute if the relational expression is true. If this comes about, nothing will happen. So far, there is no harm done.

However, there is an additional consequence, an illogical result. The cout statement The number is even will execute whether or not the relational expression is true. In other words, even if an odd number is entered, the program will output The number is even.

 Enter a whole number: 17 The number is even 

The reason the cout statement will execute whether or not the relational expression is true is that the cout statement no longer is part of the if statement. Unless you use curly braces as explained in the next section, only the first statement following the if keyword and relational expression is conditional. That first conditional statement is the empty statement, by virtue of the semicolon following the if expression.

Curly Braces Needed for Multiple Conditional  Statements

As just discussed, unless you use curly braces (explained later in this section), only the first statement following the if keyword and relational expression is conditional. For example, in the following code, only the first cout statement is conditional. The second cout statement is not, so it will execute whether the relational expression is true or false:

 if (num % 2 == 0)  cout << "The number is even" << endl;  cout << "And the number is not odd" << endl; 
Note  

The indentation tells the programmer which statement is conditional and which is not. The compiler ignores indentation.

Thus, if the user enters an odd number such as 17, the cout statement The number is even will not display because the relational expression is false. However, the following statement And the number is not odd will display because that statement does not belong to the if statement.

 Enter a whole number: 17 And the number is not odd 

If you want more than one statement to be part of the overall if statement, you must encase these statements in curly braces:

 if (num % 2 == 0)  {  cout << "The number is even" << endl;  cout << "And the number is not odd" << endl;  } 

Now the second cout statement will execute only if the if expression is true.

Forgetting these curly braces when you want multiple statements to be conditional is another common syntax error.

Don t Mistakenly Use the Assignment Operator!

The third most common syntax error is to use the assignment operator instead of the relational equality operator because the assignment operator looks like an equal sign:

 if (num % 2 = 0) // wrong operator!  cout << "The number is even" << endl; 

The result is that the if expression will not evaluate as the result of a comparison. Instead, it will evaluate the expression within the parentheses as the end result of the assignment, with a non-zero value being regarded as true, a zero value being regarded as false.

Note  

Some compilers will treat this mistake as a compiler error.




C++ Demystified(c) A Self-Teaching Guide
C++ Demystified(c) A Self-Teaching Guide
ISBN: 72253703
EAN: N/A
Year: 2006
Pages: 148

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net