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 isRaining = false;

if (!isRaining) {
    std::cout << "I don't need an umbrella" << std::endl;
}

This prints:

I don't need an umbrella

isRaining 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:

Done

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

    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 (!isRaining). Then add an else branch that prints I'll read a book.

Back

10/12

  1. 1. The if Statement
  2. 2. Blocks and Indentation
  3. 3. The else Branch
  4. 4. Comparison Operators
  5. 5. Boolean Values
  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. Summary
Next

Try it yourself

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