The Relational Operators

The relational operators (<, <=, >, <=) have their ordinary meanings and return bool values. These operators are left associative.

Because the relational operators return bools, the result of chaining these operators together is likely to be surprising:

// oops! this condition compares k to the bool result of i < jif (i < j < k) // true if k is greater than 1!

This condition groups i and j to the first < operator. The bool result of that expression is the left-hand operand of the second less-than operator. That is, k is compared to the true/false result of the first comparison! To accomplish the test we intended, we can rewrite the expression as follows:

// ok: condition is true if i is smaller than j and j is smaller ...

Get C++ Primer, Fifth Edition 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.