Relational Operators in C
In this tutorial, we will understand relational operators and their uses in the C programming language.
In this tutorial, we will understand relational operators and their uses in the C programming language.
A relational operator is a symbol that compares two values. It tells us if the values are the same or if one is greater or smaller than the other. The result of the comparison is either true or false. We can represent true as 1 and false as 0. The most commonly used relational operators are:
The following program shows the results generated by all the relational operators:
#include <stdio.h>
int main()
{
int x = 5;
int y = 4;
printf("%d\n", x == y); // 0
printf("%d\n", x != y); // 1
printf("%d\n", x > y); // 1
printf("%d\n", x >= y); // 1
printf("%d\n", x < y); // 0
printf("%d\n", x <= y); // 0
return 0;
}
Output:
0
1
1
1
0
0
The usage of these relational operators will become clear when we discuss conditionals like if-else statements.
The following table shows the precedence and associativity of relational operators (in continuation with the arithmetic operators):
Precedence | Operators | Associativity |
---|---|---|
1st | Unary + and – | Right to left |
2nd | *, /, % | Left to right |
3rd | +, – | Left to right |
4th | <, <=, >, >= | Left to right |
5th | ==, != | Left to right |
6th | = | Right to left |
Example: Solve 3 + 4 * 9 <= 10 == 5
.
Solution:
3 + 4 * 9 <= 10 == 5
3 + 36 <= 10 == 5 (4 * 9 = 36)
39 <= 10 == 5 (3 + 36 = 39)
0 == 5 (39 <= 10 = 0)
0
Leave a comment