Using relational operators in C, we compare 2 values. The comparison could be if 2 values are equal or not equal, if one value is greater than another, or lesser than another. The values can be of type int
, float
, double
, long
or char
. The result of the comparison will be 0 or 1., result 0 signifies false, and 1 signifies true.
There are 6 types of relational operators, == (equals), != (not equals), > (greater than), >= (greater than or equal), < (less than), < (less than or equal).
Equals Operator
We use equals operator to compare if two values are equals.
int a = 5, b = 10;
printf("%d", a == b); //prints 0
The equals operator consists 2 equal symbols. If you by mistake write only 1 equal, it will become an assignment operation.
int a = 5, b = 10;
printf("%d", a = b); //prints 10
In the above code snippet, we are using a single equals, that’s why the operation performed on that line is an assignment not an equals comparison.
Not Equals Operator
We use a not equals operator to test if 2 values are not equal with each other. We denote it by an exclamation followed by an equal symbol.
int a = 5, b = 10;
printf("%d", a != b); //prints 1
Greater Than Operator
We use a greater than operator to check if a value is greater than another value. We denote “greater than” operator using > symbol as we usually do in mathematics..
int a = 5, b = 10;
printf("%d", a > b); //prints 0
Greater Than or Equals Operator
We use greater than or equals operator to check if a value is greater, if not equals with another value. To write greater than or equal, we put an “equals” operator followed by “greater than” symbol, like >=.
int a = 5, b = 5;
printf("%d", a >= b); //prints 1
In the above code snippet, though a is not greater than b, since it is equals to b, so the result will be 1.
Less Than Operator
We use a less than operator to check if a value is less than another value. We denote “less than” operator using the less than symbol <.
int a = 5, b = 5;
printf("%d", a < b); //prints 0
printf("%d", a < 9); //prints 1
Less Than or Equal Operator
We use “less than or equal” operator to test if a value is less than another value or equal to itself. We denote “less than or equal” operator using less than symbol followed by equal symbol.
int a = 5, b = 5;
printf("%d", a <= b); //prints 1
printf("%d", a < 2); //prints 0