In real life, we often compare two different quantities and depending on their relation, we take some decisions. For example, we compare the price of two items, age of two persons etc. Relational operators supports these comparisons in C programming.
We use relational operators to compare two constants, variables or expressions. We generally compare two quantities of similar nature. Likewise, relational operators can only compare any two similar types. It evaluates Boolean value either true or false depending on their relation. Based on evaluated Boolean result we take decisions or execute some statements.
In C programming, there is no concept of Boolean values. C represents false with 0 and true with a non-zero integer value.
C supports six relational operators.
Operator | Description |
---|---|
> | Greater than |
< | Less than |
>= | Greater than or equal to |
<= | Less than or equal to |
== | Equals to |
!= | Not equal to |
Let us demonstrate working of each relational operator.
Suppose x, y and z are three integer variables with initial values
int x=10, y=5, z=10;
Relational operations | Result | Description |
---|---|---|
x > y | 1 | 10 > 5 is true, therefore returns 1 |
x < y | 0 | 10 < 5 is false, therefore returns 0 |
x >= z | 1 | 10 ≥ 10 is true, therefore returns 1 |
x <= y | 0 | 10 ≤ 5 is false, therefore returns 0 |
x == z | 1 | 10 = 10 is true, therefore returns 1 |
x != z | 0 | 10 ≠ 10 is false, therefore returns 0 |
You are free to use any non-zero integer value to represent true. However, C standard specifies to use 1 for representing a true value.
Important note: Do not confuse assignment =
operator with relational equals to ==
operator. Both are different and their working mechanism are different. Beginners always makes this common mistake of using =
in place of ==
. Hence use these with caution.