const int Fave = 27;

int main()

{

    using namespace std;

    int n;

    cout << "Enter a number in the range 1-100 to find ";

    cout << "my favorite number: ";

    do

    {

        cin >> n;

        if (n < Fave)

            cout << "Too low -- guess again: ";

        else if (n > Fave)

            cout << "Too high -- guess again: ";

        else

            cout << Fave << " is right!\n";

    } while (n != Fave);

    return 0;

}

Here’s some sample output from the program in Listing 6.3:

Enter a number in the range 1-100 to find my favorite number: 50

Too high -- guess again: 25

Too low -- guess again: 37

Too high -- guess again: 31

Too high -- guess again: 28

Too high -- guess again: 27

27 is right!

Conditional Operators and Bug Prevention

Many programmers reverse the more intuitive expression variable == value to value == variable in order to catch errors where the equality is mistyped as an assignment operator. For example, entering the conditional as follows is valid and will work properly:

if (3 == myNumber)

However, if you happen to mistype as follows, the compiler will generate an error message because it believes you are attempting to assign a value to a literal (3 always equals 3 and can’t be assigned another value):

if (3 = myNumber)

Suppose you made a similar mistake, using the former notation:

if (myNumber = 3)

The compiler would simply assign the value 3 to myNumber, and the block within the if would run—a very common error, and a difficult error to find. (However, many compilers will issue a warning, which you would be wise to heed.) As a general rule, writing code that allows the compiler to find errors is much easier than repairing the causes of mysterious faulty results.

Logical Expressions

Often you must test for more than one condition. For example, for a character to be a lowercase letter, its value must be greater than or equal to 'a' and less than or equal to 'z'. Or, if you ask a user to respond with a y or an n, you want to accept uppercase (Y and N) as well as lowercase. To meet this kind of need, C++ provides three logical operators to combine or modify existing expressions. The operators are logical OR, written ||; logical AND, written &&; and logical NOT, written !. Let’s examine them now.

The Logical OR Operator: ||

In English, the word or can indicate when one or both of two conditions satisfy a requirement. For example, you can go to the MegaMicro company picnic if you or your spouse work for MegaMicro, Inc. The C++ equivalent is the logical OR operator, written ||. This operator combines two expressions into one. If either or both of the original expressions is true, or nonzero, the resulting expression has the value true. Otherwise, the expression has the value false. Here are some examples:

5 == 5 || 5 == 9   // true because first expression is true

5 > 3 || 5 > 10    // true because first expression is true

5 > 8 || 5 < 10    // true because second expression is true

5 < 8 || 5 > 2     // true because both expressions are true

5 > 8 || 5 < 2     // false because both expressions are false

Because the || has a lower precedence than the relational operators, you don’t need to use parentheses in these expressions. Table 6.1 summarizes how the || operator works.

Table 6.1. The || Operator

C++ provides that the || operator is a sequence point. That is, any value changes indicated on the left side take place before the right side is evaluated. (Or in the newer parlance of C++11, the subexpression to the left of the operator is sequenced before the subexpression to the right.) For example, consider the following expression:

i++ < 6 || i == j

Suppose i originally has the value 10. By the time the comparison with j takes place, i has the value 11. Also C++ won’t bother evaluating the expression on the right if the expression on the left is true, for it only takes one true expression to make the whole logical expression true. (The semicolon and the comma operator, recall, are also sequence points.)

Listing 6.4 uses the || operator in an if statement to check for both uppercase and lowercase versions of a character. Also it uses C++’s string concatenation feature (see Chapter 4, “Compound Types”) to spread a single string over three lines.

Listing 6.4. or.cpp

// or.cpp -- using the logical OR operator

#include

int main()

{

    using namespace std;

    cout << "This program may reformat your hard disk\n"

            "and destroy all your data.\n"

            "Do you wish to continue? ";

    char ch;

    cin >> ch;

    if (ch == 'y' || ch == 'Y')             // y or Y

        cout << "You were warned!\a\a\n";

    else if (ch == 'n' || ch == 'N')        // n or N

        cout << "A wise choice ... bye\n";

    else

    cout << "That wasn't a y or n! Apparently you "

            "can't follow\ninstructions, so "

            "I'll trash your disk anyway.\a\a\a\n";

    return 0;

}

(The program doesn’t really carry out any threats.) Here is a sample run of the program in Listing 6.4:

This program may reformat your hard disk

and destroy all your data.

Do you wish to continue? N

Перейти на страницу:

Все книги серии Developer's Library

Похожие книги