In C++, comparison operators are tools used to evaluate the relationship between two values. They are crucial for decision-making in programs, enabling logic-based operations like conditional statements and loops.
Boolean Return Values
When a comparison operator is used, the result is a boolean value:
1
representstrue
.0
representsfalse
.
This helps determine whether a specific condition is met.
Comparison Example
#include <iostream> using namespace std; int main() { int speed1 = 150; int speed2 = 120; cout << (speed1 > speed2); // Returns 1 (true), because 150 is greater than 120 return 0; }
Common Comparison Operators
These operators allow programmers to compare values or variables, making logic-based decisions.
Operator | Name | Example |
---|---|---|
== | Equal to | speed1 == speed2 |
!= | Not equal | speed1 != speed2 |
> | Greater than | speed1 > speed2 |
< | Less than | speed1 < speed2 |
>= | Greater than or equal to | speed1 >= speed2 |
<= | Less than or equal to | speed1 <= speed2 |
Real-Life Example in Programming
Comparison operators help evaluate and act based on conditions. For example:
#include <iostream> using namespace std; int main() { int horsepower1 = 500; int horsepower2 = 450; if (horsepower1 > horsepower2) { cout << "Bike 1 is more powerful."; } else { cout << "Bike 2 is more powerful."; } return 0; }