Lesson 7 · 7 of 20
Comparisons and logic · C++
Compare values in C++ with ==, !=, < and >, combine conditions with &&, || and !, and print bools as true and false with std::boolalpha.

A comparison gives a `bool`: age >= 18 is false at 16. The operators are == (equal), != (not equal), <, >, <= and >=. Careful: = assigns and == compares.
By default, std::cout prints a bool as 0 or 1. After `std::boolalpha` it prints false and true, and keeps doing so until the program ends. Inside a chain of <<, comparisons go in brackets.
`&&` (and) needs both sides to be true, `||` (or) needs at least one and `!` (not) flips the value. That is why a minor can see the film with an adult, and 31.5 degrees is a hot day: it lies between 30 and 45.
C++ uses short-circuit evaluation: if the left side of && is false, the right side is never worked out. Thanks to that, boxes != 0 && items / boxes > 5 never divides by zero.
std::string values can be compared too: < follows alphabetical order, and "apple" < "banana" is true.
Code · main.cpp
#include <iostream>#include <string>int main() { int age = 16; bool withAdult = true; double temperature = 31.5; // A comparison gives a bool: true or false. bool adult = age >= 18; std::cout << "adult = " << adult << '\n'; // by default, 0 or 1 std::cout << std::boolalpha; // from now on, false or true std::cout << "adult = " << adult << '\n'; std::cout << "age == 16: " << (age == 16) << ", age != 16: " << (age != 16) << '\n'; // && (and): both must be true. || (or): at least one. ! (not) reverses. bool canEnter = adult || withAdult; std::cout << "Can see the film: " << canEnter << '\n'; bool hotDay = temperature > 30 && temperature <= 45; std::cout << "Hot day: " << hotDay << ", not hot: " << !hotDay << '\n'; // Short-circuit: if the left side decides, the right one is not evaluated. int boxes = 0, items = 12; if (boxes != 0 && items / boxes > 5) std::cout << "The boxes are full\n"; else std::cout << "No boxes to check (and no division by zero)\n"; // Strings are compared in alphabetical order. std::string a = "apple", b = "banana"; std::cout << a << " < " << b << ": " << (a < b) << '\n'; return 0;}Output · c++ -std=c++17 main.cpp -o main && ./main
adult = 0 adult = false age == 16: true, age != 16: false Can see the film: true Hot day: true, not hot: false No boxes to check (and no division by zero) apple < banana: true
Key points
- A comparison gives
trueorfalse. ==compares;=assigns.&&(and),||(or) and!(not) combine conditions.- With
&&and||, the right side is only evaluated when needed. std::boolalphaprintstrueandfalseinstead of1and0.
Exercise
Write the condition for a special offer: there is a discount if the customer is a member (bool member) or spends over 100 euros, but never on a Sunday (bool sunday). Try it with several combinations.