Relational Operators in C

Relational operators are used to compare values of two expression. Relational operators are binary operators because they require two operands to operate. An expression which contains the relational operators is called relational expression. If the relation if true then the result of the relation expression is 1, if the relation is false then the result of relation expression is 0.

Operator Description Example Result
> Greater than 1 > 2 0
>= Greater than or equal to 3 >= 2 1
< Smaller than 10 < 5 0
<= Smaller than or equal to 6 <= 7 1
== equal to 98==98 1
!= not equal to 10 != 9 1

Always remember in C a non-zero value means true and 0 means false.

The following program demonstrates relation operators.

#include<stdio.h>

int main()
{
    int x = 12, y = 13;

    printf("x = %d\n", x);
    printf("y = %d\n\n", y);

    // x is greater than y
    printf("x > y : %d\n", x > y);

    // x is greater than or equal to y
    printf("x >= y : %d\n", x >= y);

    // x is smaller than y
    printf("x < y : %d\n", x < y);

    // x is smaller than or equal to y
    printf("x <= y : %d\n", x <= y);

    // x is equal to y
    printf("x == y : %d\n", x == y);

    // x is not equal to y
    printf("x != y : %d\n", x != y);

    // Signal to operating system everything works fine
    return 0;
}

Expected Output:

x = 12
y = 13

x > y : 0
x >= y : 0
x < y : 1
x <= y : 1
x == y : 0
x != y : 1

To use relational operators to its full potential you must learn if..else statement, which we will learn in upcoming chapters.

Don't confuse assignment operator (=) with equal to operator (==). The first one is used to assign a value to the variable while the second is used to test whether values are equal or not.