C Relational Operators – Compare Values in C
Relational operators in C are used to compare two values or variables. The result of a comparison is either true (1) or false (0), which is useful in decision-making (e.g., in if
, while
, or for
statements).
What Are Relational Operators?
Relational operators help check the relationship between two expressions or variables. They return a Boolean result:
Condition | Result |
---|---|
Condition is true | 1 |
Condition is false | 0 |
List of Relational Operators in C
Operator | Name | Example | Meaning |
---|---|---|---|
== | Equal to | a == b | True if a equals b |
!= | Not equal to | a != b | True if a is not b |
> | Greater than | a > b | True if a is greater than b |
< | Less than | a < b | True if a is less than b |
>= | Greater than or equal to | a >= b | True if a is ≥ b |
<= | Less than or equal to | a <= b | True if a is ≤ b |
Example Program Using Relational Operators
#include <stdio.h>
int main() {
int a = 10, b = 5;
printf("a == b: %d\n", a == b); // 0 (false)
printf("a != b: %d\n", a != b); // 1 (true)
printf("a > b: %d\n", a > b); // 1 (true)
printf("a < b: %d\n", a < b); // 0 (false)
printf("a >= b: %d\n", a >= b); // 1 (true)
printf("a <= b: %d\n", a <= b); // 0 (false)
return 0;
}
Output:
a == b: 0
a != b: 1
a > b: 1
a < b: 0
a >= b: 1
a <= b: 0
Use Cases
if (a > b)
– Decision-makingwhile (x <= 100)
– Loopsfor (i = 0; i != n; i++)
– Iteration with condition
Best Practices
Practice | Why? |
---|---|
Always use == to compare values | Avoid accidental assignment with = |
Use parentheses for clarity | Improves readability in conditions |
Use relational operators in if or while loops | Common in control flow |
Common Mistakes to Avoid
Mistake | Why it’s Wrong |
---|---|
Using = instead of == | = assigns, doesn’t compare |
Not understanding return values | true = 1, false = 0 |
Ignoring data types | Comparing int to char without cast may confuse |