Logical Operators: not
The third logical operator, ! (an exclamation mark), is called negation. It turns a boolean value into the opposite one: !true is false and !false is true. Read it as “not”:
bool isRaining = false;
if (!isRaining) {
std::cout << "I don't need an umbrella" << std::endl;
}This prints:
I don't need an umbrellaisRaining is false, so !isRaining is true and the block runs. Read the condition as “if it isn't raining”. You could also write isRaining == false. It means the same, but ! is shorter.
Negation is most useful with boolean variables and when you combine conditions. “The shop is open and it isn't a holiday” is isOpen && !isHoliday. With comparisons, you usually don't need it: instead of “age is not at least 18”, simply write the opposite comparison, age < 18.
! applies only to what comes right after it. To negate a whole comparison or a joined condition, put it in parentheses: !(points >= 50) or !(hasLicense && hasCar). Without parentheses, the program does something else:
int points = 30;
if (!points >= 50) {
std::cout << "Failed" << std::endl;
}
std::cout << "Done" << std::endl;This prints:
DoneThe student has only 30 points, and yet the program doesn't print Failed. Here ! applies only to points: !points is false, because 30 isn't 0, and false >= 50 (that is, 0 >= 50) is false. The program compiles without an error, and the compiler only prints a warning, which you don't see here. The right way is !(points >= 50), or even simpler, points < 50.
Instructions
- 1
Write an
ifstatement that printsI'll go outsideif the internet doesn't work. Use!. - 2
Going outside is only worth it if it isn't raining. Extend the condition with
&&so that it's true only if the internet doesn't work and at the same time it isn't raining (!isRaining). Then add anelsebranch that printsI'll read a book.