C Relational and Equality Operators

The binary relational and equality operators compare their first operand to their second operand to test the validity of the specified relationship. The result of a relational expression is 1 if the tested relationship is true and 0 if it is false. The type of the result is int.

Syntax

relational-expression :

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

equality-expression :

relational-expression
equality-expression == relational-expression
equality-expression != relational-expression

The relational and equality operators test the following relationships:

Operator Relationship Tested
< First operand less than second operand
> First operand greater than second operand
<= First operand less than or equal to second operand
>= First operand greater than or equal to second operand
== First operand equal to second operand
!= First operand not equal to second operand

The first four operators in the list above have a higher precedence than the equality operators (== and !=). See the precedence information in Table 4.1.

The operands can have integral, floating, or pointer type. The types of the operands can be different. Relational operators perform the usual arithmetic conversions on integral and floating type operands. In addition, you can use the following combinations of operand types with the relational and equality operators:

Examples

The examples below illustrate relational and equality operators.

int x = 0, y = 0;
if ( x < y )

Because x and y are equal, the expression in this example yields the value 0.

char array[10];
char *p;

for ( p = array; p < &array[10]; p++ )
    *p = '\0';

The fragment in this example sets each element of array to a null character constant.

enum color { red, white, green } col;
   .
   .
   .
   if ( col == red )
   .
   .
   .

These statements declare an enumeration variable named col with the tag color. At any time, the variable may contain an integer value of 0, 1, or 2, which represents one of the elements of the enumeration set color: the color red, white, or green, respectively. If col contains 0 when the if statement is executed, any statements depending on the if will be executed.