C Relational Operators
In this page:
Equal (==) and Not Equal (!=)
== tests whether two values are equal and != tests whether they're different; both produce 1 for true or 0 for false, and mixing up == with the single = assignment operator is one of the most common C bugs.
Example: Equal (==) and Not Equal (!=)
#include <stdio.h>
int main() {
int a = 5, b = 5;
printf("%d %d", a == b, a != b);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Greater Than (>) and Greater Than or Equal (>=)
> and >= test whether the left operand is strictly greater, or greater than or equal to, the right operand -- commonly used to check upper bounds, like whether a score exceeds a passing threshold.
Example: Greater Than (>) and Greater Than or Equal (>=)
#include <stdio.h>
int main() {
int score = 75;
printf("%d %d", score > 70, score >= 75);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Less Than (<) and Less Than or Equal (<=)
< and <= test whether the left operand is strictly less, or less than or equal to, the right operand -- the mirror image of > and >=, often paired with them to check whether a value falls within a range.
Example: Less Than (<) and Less Than or Equal (<=)
#include <stdio.h>
int main() {
int age = 15;
printf("%d %d", age < 18, age <= 15);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Understanding Relational Outputs
C has no dedicated boolean type in its original standard -- relational and logical expressions simply evaluate to the integer 1 for true or 0 for false, which is why you can use their results directly in arithmetic or as an if condition.
Example: Understanding Relational Outputs
#include <stdio.h>
int main() {
int result = (5 > 3);
printf("%d", result);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Conditional Expressions
Relational operators are what make conditional logic possible -- every if statement, while loop condition, and validation check in a C program ultimately relies on one of these operators producing a true/false result.
Example: Conditional Expressions
#include <stdio.h>
int main() {
int age = 20;
if (age >= 18) {
printf("Adult");
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: