08 Beginner The Hundred
3 > 2 > 1 Is False
perfectly good math, just not in this language
#include <iostream>
int main() {
std::cout << std::boolalpha;
std::cout << "3 > 2 > 1 is " << (3 > 2 > 1) << "\n";
int temperature = 40;
if (10 < temperature < 30)
std::cout << "a comfortable " << temperature << " degrees\n";
}
Run it. What does it print?
Answer
Both lines defy the math — and the second one passes for every temperature.
Why¶
C++ has no chained comparisons: > and < are ordinary left-associative operators, and
each one produces a bool that gets fed into the next. So 3 > 2 > 1 is (3 > 2) > 1,
which is true > 1; the bool promotes to the int 1, and 1 > 1 is false.
Likewise 10 < temperature < 30 is (10 < temperature) < 30 — a 0 or 1 compared
with 30, which is always true, so the range check accepts everything. If you also
write Python, where a < b < c genuinely means what it looks like, this habit transfers
straight into the trap.
GCC catches both lines with -Wall: -Wparentheses warns "comparisons like 'X<=Y<=Z'
do not have their mathematical meaning", and -Wbool-compare adds that comparing the
result with 30 "is always true". (-Wextra alone stays silent.)
The fix¶
Write each comparison out and join them with &&:
Takeaway: every comparison yields a bool that the next comparison happily
consumes — spell ranges as a < b && b < c.
Try it: g++ -std=c++17 main.cpp -o demo && ./demo