The short answer
To compare two values, use a comparison operator. In C and C++, there are six: ==, !=, <, >, <= and >=. Each one takes a value on each side and produces a result of true or false.
The six operators
==is true when both values are equal.!=is true when the values are different.<is true when the left value is smaller.>is true when the left value is larger.<=is true when the left value is smaller or equal.>=is true when the left value is larger or equal.
How they work in code
#include <iostream>
int main() {
int x = 10;
int y = 4;
std::cout << std::boolalpha;
std::cout << (x == y) << '\n'; // false
std::cout << (x > y) << '\n'; // true
std::cout << (x <= 10) << '\n'; // true
}
The first line prints false, because 10 and 4 are not equal. The second prints true, because 10 is greater than 4. The third prints true, because x is 10, which is less than or equal to 10.
The parentheses are needed here too. << binds more tightly than these comparisons, so without them the line won’t compile.
Using a comparison in an if statement
Comparisons are most often the condition of an if statement. The block runs only when the comparison is true:
if (x > y) {
std::cout << "x is bigger\n";
}
For the rules on strings and floating-point numbers, read the full guide to c comparison operators.
Don’t mix up == and =
A single = assigns a value. It doesn’t compare anything. if (x = 4) stores 4 in x and then tests the value 4, which is true, so the check doesn’t do what you meant. The single = is covered in c assignment operators, which explains the difference in more detail.
The same operators in C
C uses the same six operators with the same meanings. The one difference is the result: in C, a comparison produces an int, 1 for true or 0 for false.