C++

THE NATURE OF TRUTH

In C++, zero is considered false, and all other values are considered true, although true is usually represented by 1. Thus, if an expression is false, it is equal to zero, and if an expression is equal to zero, it is false. If a statement is true, all you know is that it is nonzero, and any nonzero statement is true.

Relational Operators

The relational operators are used to determine whether two numbers are equal, or if one is greater or less than the other. Every relational statement evaluates to either 1 (TRUE) or 0 (FALSE). The relational operators are presented later, in Table 4.1.

If the integer variable myAge has the value 39, and the integer variable yourAge has the value 40, you can determine whether they are equal by using the relational "equals" operator:

myAge == yourAge; // is the value in myAge the same as in yourAge?

This expression evaluates to 0, or false, because the variables are not equal. The expression

myAge > yourAge; // is myAge greater than yourAge?

evaluates to 0 or false.

WARNING: Many novice C++ programmers confuse the assignment operator (=) with the equals operator (==). This can create a nasty bug in your program.

There are six relational operators: equals (==), less than (<), greater than (>), less than or equal to (<=), greater than or equal to (>=), and not equals (!=). Table 4.1 shows each relational operator, its use, and a sample code use.

Table 4.1. The Relational Operators.

Name Operator 

Sample Evaluates

Equals == 

100 == 50; false
50 == 50; true

Not Equals !=

100 != 50; true
50 != 50; false

Greater Than >

100 > 50; true
50 > 50; false

Greater Than >=

100 >= 50; true
or Equals 50 >= 50; true

Less Than < 1

00 < 50; false
50 < 50; false

Less Than <=

100 <= 50; false
or Equals 50 <= 50; true

DO remember that relational operators return the value 1 (true) or 0 (false). DON’T confuse the assignment operator (=) with the equals relational operator (==). This is one of the most common C++ programming mistakes—be on guard for it.

The if Statement

Normally, your program flows along line by line in the order in which it appears in your source code. The if statement enables you to test for a condition (such as whether two variables are equal) and branch to different parts of your code, depending on the result.

The simplest form of an if statement is this: 

if (expression)

statement;

The expression in the parentheses can be any expression at all, but it usually contains one of the relational expressions. If the expression has the value 0, it is considered false, and the statement is skipped. If it has any nonzero value, it is considered true, and the statement is executed. Consider the following example:

if (bigNumber > smallNumber)

bigNumber = smallNumber;

This code compares bigNumber and smallNumber. If bigNumber is larger, the second line sets its value to the value of smallNumber.

Because a block of statements surrounded by braces is exactly equivalent to a single statement, the following type of branch can be quite large and powerful:

if (expression)

{

statement1;

statement2;

statement3;

}

Here’s a simple example of this usage:

if (bigNumber > smallNumber)

{

bigNumber = smallNumber;

cout << "bigNumber: " << bigNumber << "\n";

cout << "smallNumber: " << smallNumber << "\n";

}

This time, if bigNumber is larger than smallNumber, not only is it set to the value of smallNumber, but an informational message is printed. Listing 4.4 shows a more detailed example of branching based on relational operators.

Listing 4.4. A demonstration of branching based on relational operators.

1: // Listing 4.4 - demonstrates if statement

2: // used with relational operators

3: #include <iostream.h>

4: int main()

5: {

6: int RedSoxScore, YankeesScore;

7: cout << "Enter the score for the Red Sox: ";

8: cin >> RedSoxScore;

9:

10: cout << "\nEnter the score for the Yankees: ";

11: cin >> YankeesScore;

12:

13: cout << "\n";

14:

15: if (RedSoxScore > YankeesScore)

16: cout << "Go Sox!\n";

17:

18: if (RedSoxScore < YankeesScore)

19: {

20: cout << "Go Yankees!\n";

21: cout << "Happy days in New York!\n";

22: }

23:

24: if (RedSoxScore == YankeesScore)

25: {

26: cout << "A tie? Naah, can’t be.\n";

27: cout << "Give me the real score for the Yanks: ";

28: cin >> YankeesScore;

29:

30: if (RedSoxScore > YankeesScore)

31: cout << "Knew it! Go Sox!";

32:

33: if (YankeesScore > RedSoxScore)

34: cout << "Knew it! Go Yanks!";

35:

36: if (YankeesScore == RedSoxScore)

37: cout << "Wow, it really was a tie!";

38: }

39:

40: cout << "\nThanks for telling me.\n";

41: return 0;

42: }

Output: 

Enter the score for the Red Sox: 10

Enter the score for the Yankees: 10

A tie? Naah, can’t be

Give me the real score for the Yanks: 8

Knew it! Go Sox!

Thanks for telling me.

Analysis: This program asks for user input of scores for two baseball teams, which are stored in integer variables. The variables are compared in the if statement on lines 15, 18, and 24.
If one score is higher than the other, an informational message is printed. If the scores are equal, the block of code that begins on line 24 and ends on line 38 is entered. The second score is requested again, and then the scores are compared again.

Note that if the initial Yankees score was higher than the Red Sox score, the if statement on line 15 would evaluate as FALSE, and line 16 would not be invoked. The test on line 18 would evaluate as true, and the statements on lines 20 and 21 would be invoked. Then the if statement on line 24 would be tested, and this would be false (if line 18 was true). Thus, the program would skip the entire block, falling through to line 39.

In this example, getting a true result in one if statement does not stop other if statements from being tested.

Indentation Styles

Listing 4.3 shows one style of indenting if statements. Nothing is more likely to create a religious war, however, than to ask a group of programmers what is the best style for brace alignment. Although there are dozens of variations, these appear to be the favorite three:

· Putting the initial brace after the condition and aligning the closing brace under the if to close the statement block.

if (expression){

statements

}

· Aligning the braces under the if and indenting the statements.

if (expression)

{

statements

}

· Indenting the braces and statements.

if (expression)

{

statements

}

This tutorial uses the middle alternative, because I find it easier to understand where blocks of statements begin and end if the braces line up with each other and with the condition being tested. Again, it doesn’t matter much which style you choose, as long as you are consistent with it.

else

Often your program will want to take one branch if your condition is true, another if it is false. In Listing 4.3, you wanted to print one message (Go Sox!) if the first test (RedSoxScore > Yankees) evaluated TRUE, and another message (Go Yanks!) if it evaluated FALSE.

The method shown so far, testing first one condition and then the other, works fine but is a bit cumbersome. The keyword else can make for far more readable code: 

if (expression)

statement;

else

statement;

Listing 4.5. Demonstrating the else keyword.

1: // Listing 4.5 - demonstrates if statement

2: // with else clause

3: #include <iostream.h>

4: int main()

5: {

6: int firstNumber, secondNumber;

7: cout << "Please enter a big number: ";

8: cin >> firstNumber;

9: cout << "\nPlease enter a smaller number: ";

10: cin >> secondNumber;

11: if (firstNumber > secondNumber)

12: cout << "\nThanks!\n";

13: else

14: cout << "\nOops. The second is bigger!";

15:

16: return 0;

17: }

Output:

Please enter a big number: 10

Please enter a smaller number: 12

Oops. The second is bigger!

Analysis: The if statement on line 11 is evaluated. If the condition is true, the statement on line 12 is run; if it is false, the statement on line 14 is run. If the else clause on line 13 were removed, the statement on line 14 would run whether or not the if statement was true. Remember, the if statement ends after line 12. If the else was not there, line 14 would just be the next line in the program.

Remember that either or both of these statements could be replaced with a block of code in braces.

The if Statement

The syntax for the if statement is as follows: Form 1

if (expression)

statement;

next statement;

If the expression is evaluated as TRUE, the statement is executed and the program continues with the next statement. If the expression is not true, the statement is ignored and the program jumps to the next statement. Remember that the statement can be a single statement ending with a semicolon or a block enclosed in braces. Form 2

if (expression)

statement1;

else

statement2;

next statement;

If the expression evaluates TRUE, statement1 is executed; otherwise, statement2 is executed. Afterwards, the program continues with the next statement. Example 1

Example

if (SomeValue < 10)

cout << "SomeValue is less than 10");

else

cout << "SomeValue is not less than 10!");

cout << "Done." << endl;

Advanced if Statements

It is worth noting that any statement can be used in an if or else clause, even another if or else statement. Thus, you might see complex if statements in the following form:

if (expression1)

{

if (expression2)

statement1;

else

{

if (expression3)

statement2;

else

statement3;

}

}

else

statement4;

This cumbersome if statement says, "If expression1 is true and expression2 is true, execute statement1. If expression1 is true but expression2 is not true, then if expression3 is true execute statement2. If expression1 is true but expression2 and expression3 are false, execute statement3. Finally, if expression1 is not true, execute statement4." As you can see, complex if statements can be confusing!

Listing 4.6 gives an example of such a complex if statement.

Listing 4.6. A complex, nested if statement.

1: // Listing 4.5 - a complex nested

2: // if statement

3: #include <iostream.h>

4: int main()

5: {

6: // Ask for two numbers

7: // Assign the numbers to bigNumber and littleNumber

8: // If bigNumber is bigger than littleNumber,

9: // see if they are evenly divisible

10: // If they are, see if they are the same number

11:

12: int firstNumber, secondNumber;

13: cout << "Enter two numbers.\nFirst: ";

14: cin >> firstNumber;

15: cout << "\nSecond: ";

16: cin >> secondNumber;

17: cout << "\n\n";

18:

19: if (firstNumber >= secondNumber)

20: {

21: if ( (firstNumber % secondNumber) == 0) // evenly divisible?

22: {

23: if (firstNumber == secondNumber)

24: cout << "They are the same!\n";

25: else

26: cout << "They are evenly divisible!\n";

27: }

28: else

29: cout << "They are not evenly divisible!\n";

30: }

31: else

32: cout << "Hey! The second one is larger!\n";

33: return 0;

34: }

Output:

Enter two numbers.

First: 10

Second: 2

They are evenly divisible!

Analysis: Two numbers are prompted for one at a time, and then compared. The first if statement, on line 19, checks to ensure that the first number is greater than or equal to the second. If not, the else clause on line 31 is executed. If the first if is true, the block of code beginning on line 20 is executed, and the second if statement is tested, on line 21. This checks to see whether the first number modulo the second number yields no remainder. If so, the numbers are either evenly divisible or equal. The if statement on line 23 checks for equality and displays the appropriate message either way.

If the if statement on line 21 fails, the else statement on line 28 is executed.

Using Braces in Nested if Statements

Although it is legal to leave out the braces on if statements that are only a single statement, and it is legal to nest if statements, such as

if (x > y) // if x is bigger than y

if (x < z) // and if x is smaller than z

x = y; // then set x to the value in z

when writing large nested statements, this can cause enormous confusion. Remember, whitespace and indentation are a convenience for the programmer; they make no difference to the compiler. It is easy to confuse the logic and inadvertently assign an else statement to the wrong if statement. Listing 4.7 illustrates this problem.

Listing 4.7. A demonstration of why braces help clarify which else statement goes with which if statement.

////1: // Listing 4.7 - demonstrates why braces

2: // are important in nested if statements

3: #include <iostream.h>

4: int main()

5: {

6: int x;

7: cout << "Enter a number less than 10 or greater than 100: ";

8: cin >> x;

9: cout << "\n";

10:

11: if (x > 10)

12: if (x > 100)

13: cout << "More than 100, Thanks!\n";

14: else // not the else intended!

15: cout << "Less than 10, Thanks!\n";

16:

17: return 0;

18: }

Output: 

Enter a number less than 10 or greater than 100: 20

Less than 10, Thanks!

Analysis: The programmer intended to ask for a number between 10 and 100, check for the correct value, and then print a thank-you note. If the if statement on line 11 evaluates TRUE, the following statement (line 12) is executed. In this case, line 12 executes when the number entered is greater than 10. Line 12 contains an if statement also. This if statement evaluates TRUE if the number entered is greater than 100. If the number is not greater than 100, the statement on line 13 is executed.

If the number entered is less than or equal to 10, the if statement on line 10 evaluates to FALSE. Program control goes to the next line following the if statement, in this case line 16. If you enter a number less than 10, the output is as follows:

Enter a number less than 10 or greater than 100: 9

The else clause on line 14 was clearly intended to be attached to the if statement on line 11, and thus is indented accordingly. Unfortunately, the else statement is really attached to the if statement on line 12, and thus this program has a subtle bug.

It is a subtle bug because the compiler will not complain. This is a legal C++ program, but it just doesn’t do what was intended. Further, most of the times the programmer tests this program, it will appear to work. As long as a number that is greater than 100 is entered, the program will seem to work just fine.

Listing 4.8 fixes the problem by putting in the necessary braces.

Listing 4.8. A demonstration of the proper use of braces with an if statement

1: // Listing 4.8 - demonstrates proper use of braces

2: // in nested if statements

3: #include <iostream.h>

4: int main()

5: {

6: int x;

7: cout << "Enter a number less than 10 or greater than 100: ";

8: cin >> x;

9: cout << "\n";

10:

11: if (x > 10)

12: {

13: if (x > 100)

14: cout << "More than 100, Thanks!\n";

15: }

16: else // not the else intended!

17: cout << "Less than 10, Thanks!\n";

18: return 0;

19: }

Output: 

Enter a number less than 10 or greater than 100: 20

Analysis: The braces on lines 12 and 15 make everything between them into one statement, and now the else on line 16 applies to the if on line 11 as intended. The user typed 20, so the if statement on line 11 is true; however, the if statement on line 13 is false, so nothing is printed. It would be better if the programmer put another else clause after line 14 so that errors would be caught and a message printed.

NOTE: The programs shown in this book are written to demonstrate the particular issues being discussed. They are kept intentionally simple; there is no attempt to "bulletproof" the code to protect against user error. In professional-quality code, every possible user error is anticipated and handled gracefully.

Back to Index