Equality and Relational Operators in C

In this blog post, you will learn equality and relational operators in C programming with the help of example code. So let’s first understand what relation operators are.

The relational and equality operators are binary operators. They compare their first operand to their second operand to test the validity of the specified relationship. If the specified relationship is true, then the result of a relational expression is 1 otherwise 0.

Note: The result has type int.

 

List of relational and equality operators:

The following table contains relational and equality operators along with some examples. The last two operators (== and !=) in the list have lower precedence than the other relational operators.

Operator Relationship Tested Example Result
> First operand greater than second operand 10 > 2 1
>= First operand greater than or equal to second operand 13 >= 14 0
< First operand less than second operand 40 < 15 0
<= First operand less than or equal to second operand 16 <= 27 1
== First operand equal to second operand 18==17 0
!= First operand not equal to second operand 13 != 5 1

 

Relational Operators in C With Example:

The following example illustrates relational and equality operators.

#include<stdio.h>

int main()
{
    int a = 6, b = 27;

    printf("a = %d\n", a);
    printf("b = %d\n\n", b);

    // Test a is greater than b?
    printf("a >  b : %d\n", a > b);

    // Test a is greater than or equal to b?
    printf("a >= b : %d\n", a >= b);

    // Test a is smaller than b?
    printf("a <  b : %d\n", a < b);

    // Test a is smaller than or equal to b?
    printf("a <= b : %d\n", a <= b);

    // Test a is equal to b?
    printf("a == b : %d\n", a == b);

    // Test a is not equal to b?
    printf("a != b : %d\n", a != b);

    return 0;
}

Output:

Relational Operators in C Aticleworld

 

Precedence And Associativity of Relational Operator:

The precedence of equality operators == and != are the same and they associate from left to right. Similarly precedence of <, <=, > and >= relational operators are the same and they also associate from left to right.

The point which is important to know is that the precedence of equality operators is lower than other relational operators.

Let’s see an example to understand the precedence and associativity of relational operators. But it is my recommendation you must use proper braces in your code to avoid any confusion and undesired results.

Example 1:

int c = 0 == 5 > 7;

Step 1: Evaluate 5 > 7 (precedence high among mentioned operator).

int c = 0 == 0;

Step 2: Evaluate 0 == 0 (precedence higher than =).

int c = 1;

Step 3: Evaluate c = 1

Now c contains 1.

 

Example 2:

int c = 0 < 15 > 7(precedence same so associate from left to right).

Step 1: Evaluate 0 < 15

int c = 1 > 7

Step 2: Evaluate 1 > 7 (precedence higher than =)

int c = 0

Step 3: Evaluate c = 0

Now c contains 0.

 

Recommended Post: