Relational Operators

The binary relational operators determine the following relationships:

Syntax

relational-expression :

shift-expression
relational-expression < shift-expression
relational-expression > shift-expression
relational-expression <= shift-expression
relational-expression >= shift-expression

The relational operators have left-to-right associativity. Both operands of relational operators must be of arithmetic or pointer type. They yield values of type int. The value returned is 0 if the relationship in the expression is false; otherwise, it is 1. Consider the following code, which demonstrates several relational expressions:

#include <iostream.h>

void main()
{
    cout << "The true expression 3 > 2 yields: "
         << (3 > 2) << "\n";
    cout << "The false expression 20 < 10 yields: "
         << (20 < 10) << "\n";
    cout << "The expression 10 < 20 < 5 yields: "
         << (10 < 20 < 5) << "\n";
}

The output from this program is:

The true expression 3 > 2 yields 1
The false expression 20 < 10 yields 0
The expression 10 < 20 < 5 yields 1

The expressions in the preceding example must be enclosed in parentheses because the insertion operator (<<) has higher precedence than the relational operators. Therefore, the first expression without the parentheses would be evaluated as:

(cout << "The true expression 3 > 2 yields: " << 3) < (2 << "\n");

Note that the third expression evaluates to 1 — because of the left-to-right associativity of relational operators, the explicit grouping of the expression 10 < 20 < 5 is:

(10 < 20) < 5

Therefore, the test performed is:

1 < 5

and the result is 1 (or true).

The usual arithmetic conversions covered in Arithmetic Conversions in Chapter 3 are applied to operands of arithmetic types.