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 is_raining = false;
if (!is_raining) {
printf("I don't need an umbrella\n");
}This prints:
I don't need an umbrellais_raining is false, so !is_raining is true and the block runs. Read the condition as “if it isn't raining”. You could also write is_raining == 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 is_open && !is_holiday. 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 !(has_licence && has_car). Without the parentheses, you get something else:
int points = 30;
if (!points >= 50) {
printf("Failed\n");
}The compiler reports:
error: logical not is only applied to the left hand side of this comparison [-Werror,-Wlogical-not-parentheses]In !points >= 50, the ! applies only to points. !points is false, that is 0, because 30 isn't 0, and 0 >= 50 is false, so the program would never print Failed. Many compilers let this through with just a warning; here it's an error. The right way is !(points >= 50), or even simpler, points < 50.
Instructions
- 1
In place of the comment, 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 (!is_raining). Then add anelsebranch that printsI'll read a book.