2.7 Decision Making: Equality and Relational Operators

We now introduce C++’s if statement, which allows a program to take alternative action based on whether a condition is true or false. Conditions in if statements can be formed by using the relational operators and equality operators summarized in Fig. 2.12. The relational operators all have the same level of precedence and associate left to right. The equality operators both have the same level of precedence, which is lower than that of the relational operators, and associate left to right.

Fig. 2.12 Relational and equality operators.

Algebraic relational or equality operator C++ relational or equality operator Sample C++ condition Meaning of C++ condition
Relational operators      
> > x > y x is greater than y
< < x < y x is less than y
>= x >= y x is greater than or equal to y
<= x <= y x is less than or equal to y
Equality operators      
= == x == y x is equal to y
!= x != y x is not equal to y

Common Programming Error 2.3

Reversing the order of the pair of symbols in the operators !=, >= and <= (by writing them as =!, => and =<, respectively) is normally a syntax error. In some cases, writing != as =! will not be a syntax error, but almost certainly will be a logic error that has an effect at execution time. You’ll understand why when you learn about logical operators in Chapter 5. A fatal logic error causes a program to fail and terminate prematurely. A nonfatal logic error allows a program to continue executing, but usually produces incorrect results.

 

Common Programming Error 2.4

Confusing the equality operator == with the assignment operator = results in logic errors. We like to read the equality operator as “is equal to” or “double equals,” and the assignment operator as “gets” or “gets the value of” or “is assigned the value of.” As you’ll see in Section 5.12, confusing these operators may not necessarily cause an easy-to-recognize syntax error, but may cause subtle logic errors.

Using the if Statement

The following example (Fig. 2.13) uses six if statements to compare two numbers input by the user. If a given if statement’s condition is true, the output statement in the body of that if statement executes. If the condition is false, the output statement in the body does not execute.

Fig. 2.13 Comparing integers using if statements, relational operators and equality operators.

Alternate View

 1   // Fig. 2.13: fig02_13.cpp
 2   // Comparing integers using if statements, relational operators
 3   // and equality operators.
 4   #include <iostream> // enables program to perform input and output
 5
 6   using std::cout; // program uses cout
 7   using std::cin; // program uses cin  
 8   using std::endl; // program uses endl
 9
10   // function main begins program execution
11   int main() {
12      int number1{0}; // first integer to compare (initialized to 0)
13      int number2{0}; // second integer to compare (initialized to 0)
14
15      cout << "Enter two integers to compare: "; // prompt user for data
16      cin >> number1 >> number2; // read two integers from user
17
18      if (number1 == number2) {                       
19         cout << number1 << " == " << number2 << endl;
20      }                                               
21
22      if (number1 != number2) {
23         cout << number1 << " != " << number2 << endl;
24      }
25
26      if (number1 < number2) {
27         cout << number1 << " < " << number2 << endl;
28      }
29
30      if (number1 > number2) {
31         cout << number1 << " > " << number2 << endl;
32      }
33
34      if (number1 <= number2) {
35         cout << number1 << " <= " << number2 << endl;
36      }
37
38      if (number1 >= number2) {
39         cout << number1 << " >= " << number2 << endl;
40      }
41    } // end function main

Enter two integers to compare: 3 7
3 != 7
3 < 7
3 <= 7

Enter two integers to compare: 22 12
22 != 12
22 > 12
22 >= 12

Enter two integers to compare: 7 7
7 == 7
7 <= 7
7 >= 7

using Declarations

Lines 6–8


using std::cout; // program uses cout
using std::cin; // program uses cin
using std::endl; // program uses endl

are using declarations that eliminate the need to repeat the std:: prefix as we did in earlier programs. We can now write cout instead of std::cout, cin instead of std::cin and endl instead of std::endl, respectively, in the remainder of the program.

In place of lines 6–8, many programmers prefer to provide the using directive


using namespace std;

which enables a program to use all the names in any standard C++ header (such as <iostream>) that a program might include. From this point forward in the book, we’ll use the preceding directive in our programs.2

Variable Declarations and Reading the Inputs from the User

Lines 12–13


int number1{0}; // first integer to compare (initialized to 0)
int number2{0}; // second integer to compare (initialized to 0)

declare the variables used in the program and initialize them to 0.

Line 16


cin >> number1 >> number2; // read two integers from user

uses cascaded stream extraction operations to input two integers. Recall that we’re allowed to write cin (instead of std::cin) because of line 7. First a value is read into variable number1, then a value is read into variable number2.

Comparing Numbers

The if statement in lines 18–20


if (number1 == number2) {
   cout << number1 << " == " << number2 << endl;
}

compares the values of variables number1 and number2 to test for equality. If the values are equal, the statement in line 19 displays a line of text indicating that the numbers are equal. If the conditions are true in one or more of the if statements starting in lines 22, 26, 30, 34 and 38, the corresponding body statement displays an appropriate line of text.

Each if statement in Fig. 2.13 contains a single body statement that’s indented. Also notice that we’ve enclosed each body statement in a pair of braces, { }, creating what’s called a compound statement or a block.

Good Programming Practice 2.9

Indent the statement(s) in the body of an if statement to enhance readability.

 

Error-Prevention Tip 2.2

You don’t need to use braces, { }, around single-statement bodies, but you must include the braces around multiple-statement bodies. You’ll see later that forgetting to enclose multiple-statement bodies in braces leads to errors. To avoid errors, as a rule, always enclose an if statement’s body statement(s) in braces.

 

Common Programming Error 2.5

Placing a semicolon immediately after the right parenthesis after the condition in an if statement is often a logic error (although not a syntax error). The semicolon causes the body of the if statement to be empty, so the if statement performs no action, regardless of whether or not its condition is true. Worse yet, the original body statement of the if statement now becomes a statement in sequence with the if statement and always executes, often causing the program to produce incorrect results.

White Space

Note our use of blank lines in Fig. 2.13. We inserted these for readability. Recall that white-space characters, such as tabs, newlines and spaces, are normally ignored by the compiler. So, statements may be split over several lines and may be spaced according to your preferences. It’s a syntax error to split identifiers, strings (such as "hello") and constants (such as the number 1000) over several lines.

Good Programming Practice 2.10

A lengthy statement may be spread over several lines. If a statement must be split across lines, choose meaningful breaking points, such as after a comma in a comma-separated list, or after an operator in a lengthy expression. If a statement is split across two or more lines, indent all subsequent lines and left-align the group of indented lines.

Operator Precedence

Figure 2.14 shows the precedence and associativity of the operators introduced in this chapter. The operators are shown top to bottom in decreasing order of precedence. All these operators, with the exception of the assignment operator =, associate from left to right. Addition is left-associative, so an expression like x + y + z is evaluated as if it had been written (x + y) + z. The assignment operator = associates from right to left, so an expression such as x = y = 0 is evaluated as if it had been written x = (y = 0), which, as we’ll soon see, first assigns 0 to y, then assigns the result of that assignment—0—to x.

Fig. 2.14 Precedence and associativity of the operators discussed so far.

Operators Associativity Type
()       [See caution in Fig. 2.10] grouping parentheses
* / %   left to right multiplicative
+ -     left to right additive
<< >>     left to right stream insertion/extraction
< <= > >= left to right relational
== !=     left to right equality
=       right to left assignment

Good Programming Practice 2.11

Refer to the operator precedence and associativity chart (Appendix A) when writing expressions containing many operators. Confirm that the operators in the expression are performed in the order you expect. If you’re uncertain about the order of evaluation in a complex expression, break the expression into smaller statements or use parentheses to force the order of evaluation, exactly as you’d do in an algebraic expression. Be sure to observe that some operators such as assignment (=) associate right to left rather than left to right.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset