COMPARING VALUES

Unless you want to make decisions on a whim, you need a mechanism for comparing things. This involves some new operators called relational operators. Because all information in your computer is ultimately represented by numerical values (in the last chapter you saw how character information is represented by numeric codes), comparing numerical values is the essence of all decision making. You have six operators for comparing two values:

image

NOTE The “equal to” comparison operator has two successive = signs. This is not the same as the assignment operator, which consists only of a single = sign. It’s a common mistake to inadvertently use the assignment operator instead of the comparison operator, so watch out for this.

Each operator compares the values of two operands and returns one of the two possible values of type bool: true if the comparison is true, or false if it is not. You can see how this works by having a look at a few simple examples. The operands can be variables, literals, or expressions. Suppose you have created integer variables i and j with the values 10 and −5, respectively. The expressions,

   i > j      i != j      j > -8      i <= j + 15

all return the value true.

Assume that you have defined the following variables:

char first = 'A', last = 'Z';

Here are some examples of comparisons using these:

first == 65      first < last     'E' <= first     first != last

All four ...

Get Ivor Horton's Beginning Visual C++ 2012 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.