Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

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 umbrella

is_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. 1

    In place of the comment, write an if statement that prints I'll go outside if the internet doesn't work. Use !.

  2. 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 an else branch that prints I'll read a book.

Back

10/13

  1. 1. The if Statement
  2. 2. Blocks and Indentation
  3. 3. The else Branch
  4. 4. Comparison Operators
  5. 5. True and False
  6. 6. More Options: else if
  7. 7. Quiz: else if
  8. 8. Logical Operators: and
  9. 9. Logical Operators: or
  10. 10. Logical Operators: not
  11. 11. Nested Conditions
  12. 12. The switch Statement
  13. 13. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.