< Previous | Contents | Next >
Probably the most common expression you’ll use with if statements involves comparing values using the relational operators. That’s just what I’ll demon- strate next. I test to see whether the score is greater than or equal to 250.
if (score >= 250)
{
cout << "You scored 250 or more. Decent.\n\n";
}
Because score is 1000, the block is executed, displaying the message that the player earned a decent score. If score had been less than 1000, the block would have been skipped and the program would have continued with the statement following the block.
Tra p
The equal to relational operator is == (two equal signs in a row). Don’t confuse it with = (one equal sign), which is the assignment operator.
While it’s not illegal to use the assignment operator instead of the equal to relational operator, the results might not be what you expect. Take a look at this code:
int score = 500; if (score = 1000)
{
cout << " You scored 1000 or more. Impressive!\n";
}
As a result of this code, score is set to 1000 and the message, “You scored 1000 or more. Impressive!” is displayed. Here’s what happens: Although score is 500 before the if statement, that changes. When the expression of the if statement, (score = 1000), is evaluated, score is assigned 1000. The assignment statement evaluates to 1000, and because that’s a non-zero value, the expression is interpreted as true. As a result, the string is displayed.
Be on guard for this type of mistake. It’s easy to make and in some cases (like this one), it won’t cause a compile error.