Before a program can make decisions, it needs to ask questions like “is the age at least 18?”. In C++ these questions are made with comparison operators. The answer is always true or false – a bool.
| Operator | Question | Example | Result |
|---|---|---|---|
== | equal to? | 5 == 5 | true |
!= | not equal to? | 5 != 3 | true |
< | less than? | 2 < 8 | true |
> | greater than? | 2 > 8 | false |
<= | less than or equal? | 4 <= 4 | true |
>= | greater than or equal? | 3 >= 9 | false |
#include <iostream>
using namespace std;
int main() {
int age = 20;
cout << boolalpha; // print true/false as words
cout << (age >= 18) << "\n";
cout << (age == 21) << "\n";
cout << (age != 21) << "\n";
return 0;
}Output
true false true
Common mistake:
=and==are different!=puts a value in a variable.==asks if two values are equal.
Strings can be compared too. == checks if two texts are exactly the same (capital letters count!):
#include <iostream>
#include <string>
using namespace std;
int main() {
string password = "dragon";
cout << boolalpha;
cout << (password == "dragon") << "\n";
cout << (password == "Dragon") << "\n";
return 0;
}Output
true false