Comparison Operators
The symbols < and > that you've used in conditions are comparison operators: they compare two values, and the result is either true or false. C++ has six of them:
==equal to:5 == 5!=not equal to:5 != 3>greater than:5 > 3<less than:3 < 5>=greater than or equal to:5 >= 5<=less than or equal to:3 <= 5
All the examples in the list are true. In !=, >= and <=, the equals sign always comes second, with no space in between. Watch the difference between > and >= at the boundary: 18 > 18 is false, but 18 >= 18 is true. “18 or older” is therefore age >= 18.
“Equal” is written with two equals signs, ==, because a single one already has a job: points = 10 assigns, which means it stores 10 in the variable points. points == 10 compares: it asks whether points holds 10, and changes nothing.
Writing = instead of == in a condition is one of the most common mistakes. In C++ it's especially treacherous, because the program compiles and runs:
int points = 7;
if (points = 10) {
std::cout << "Full marks!" << std::endl;
}
std::cout << "Points: " << points << std::endl;This prints:
Full marks!
Points: 10points = 10 in the condition doesn't compare anything. It stores 10 in points, and that value is then used as the condition. C++ treats every number except 0 as true, so the condition is always true, whatever points held before, and the original 7 points are gone as well. The compiler only prints a warning about it, which you don't see in this editor. When a program runs a block it shouldn't, check first whether the condition has = instead of ==.
You can compare text as well as numbers:
std::string password = "kitten42";
if (password == "kitten42") {
std::cout << "Welcome back" << std::endl;
} else {
std::cout << "Wrong password" << std::endl;
}This prints:
Welcome backAs in every program with std::string, don't forget #include <string> at the top. Two texts are equal only if they match exactly, character by character. Upper and lower case letters are different characters: when the variable name holds "Anna", name == "anna" is false. "kitten42 " with a space at the end is a different text, too. Don't forget the quotes around the text you compare with. Without them, password == kitten42 makes the compiler look for a variable called kitten42 and report error: use of undeclared identifier 'kitten42'.
Instructions
- 1
An online shop gives a gift to its 100th customer. Run the program: it prints the congratulations and
Customer number 100, although this is customer number 57. Fix the condition so that it compares. Then the program prints onlyCustomer number 57. - 2
The shop delivers to Czechia the next day and everywhere else within 3 days. At the end of the program, write an
ifstatement with anelsebranch: ifcountryis equal to"Czechia", printDelivery tomorrow, otherwise printDelivery in 3 days. The program prints:Customer number 57 Delivery in 3 days