๐ C++ Relational Operators โ Comparing Values in C++
๐งฒ Introduction โ What Are Relational Operators?
Relational operators in C++ are used to compare two values or expressions. They return a boolean result (true or false) based on the relationship between operands. These operators are widely used in conditional statements, loops, and logic-based decisions.
๐ฏ In this guide, youโll learn:
- List of relational operators in C++
- Syntax and use cases
- Examples in
if,while, andforstatements - Common mistakes to avoid
๐ List of C++ Relational Operators
| Operator | Symbol | Description | Example | Result |
|---|---|---|---|---|
| Equal to | == | True if both operands are equal | a == b | true if a = b |
| Not equal to | != | True if operands are not equal | a != b | true if a โ b |
| Greater than | > | True if left operand is greater | a > b | true if a > b |
| Less than | < | True if left operand is smaller | a < b | true if a < b |
| Greater or equal | >= | True if left operand โฅ right | a >= b | true if a โฅ b |
| Less or equal | <= | True if left operand โค right | a <= b | true if a โค b |
โ๏ธ Example โ Relational Operators in Action
#include <iostream>
using namespace std;
int main() {
int x = 10, y = 20;
cout << (x == y) << endl; // 0 (false)
cout << (x != y) << endl; // 1 (true)
cout << (x < y) << endl; // 1 (true)
return 0;
}
๐งช Relational Operators in Conditional Statements
โ
if Statement
if (age >= 18) {
cout << "You are eligible to vote.";
}
๐ while Loop
while (score < 100) {
score += 10;
}
๐ for Loop
for (int i = 1; i <= 5; i++) {
cout << i << " ";
}
โ ๏ธ Common Mistakes
| โ Mistake | โ Fix |
|---|---|
Using = instead of == | if (a == b) compares; a = b assigns |
| Comparing different types | Cast if needed: if ((float)a == b) |
Confusing != and == | Double-check logic to avoid incorrect conditions |
๐ง Best Practices
- Use parentheses to clarify comparisons in complex expressions
- Always use
==for comparison, not= - Relational operators return
0(false) or1(true)
๐ Summary โ Recap & Next Steps
๐ Key Takeaways:
- Relational operators are essential for comparing values
- They return
true(1) orfalse(0) - Commonly used in conditional logic and loops
- Use
==carefully to avoid assignment mistakes
โ๏ธ Real-World Relevance:
These operators drive user authentication, form validation, loop conditions, and game logic in C++ applications.
โ FAQs โ C++ Relational Operators
โ What does == do in C++?
โ
Compares two values and returns true if they’re equal.
โ What’s the difference between == and =?
โ
== is comparison; = is assignment.
โ Can relational operators be used with floats?
โ
Yes, but beware of precision issues. Prefer fabs(a - b) < epsilon.
โ Can I chain comparisons like a < b < c?
โ No. Break it down: a < b && b < c
โ Do relational operators work on characters?
โ
Yes. 'a' < 'z' returns true based on ASCII values.
Share Now :
