Logical Operators: or

The second logical operator is || (two vertical bars in a row), which means “or”. “If it's Saturday or Sunday, it's the weekend”:

std::string day = "Sunday";

if (day == "Saturday" || day == "Sunday") {
    std::cout << "It's the weekend" << std::endl;
}

This prints:

It's the weekend

A condition joined with || is true if at least one of its parts is true. It's false only if all of them are false:

  • true || true is true
  • true || false is true
  • false || true is true
  • false || false is false

A common mistake is to shorten the condition the way we speak: day == "Saturday" || "Sunday". The right part is then just the text "Sunday", not a comparison. Text in quotes counts as true in a condition, so the whole condition is always true, even on a Monday. And the program compiles without an error or even a warning. Each part needs its own comparison: day == "Saturday" || day == "Sunday".

You can use && and || in one condition. Just as multiplication goes before addition, && goes before ||. Group what belongs together with parentheses, just like in math:

std::string day = "Saturday";
int temperature = 15;

if ((day == "Saturday" || day == "Sunday") && temperature > 20) {
    std::cout << "We're going on a trip" << std::endl;
} else {
    std::cout << "We're staying home" << std::endl;
}

This prints:

We're staying home

The part in parentheses is evaluated first: it's Saturday, so it's true. But temperature > 20 is false, and true && false is false. Without the inner parentheses, the program would first join day == "Sunday" && temperature > 20, and the condition would be true every Saturday, whatever the weather. The outer parentheses belong to the if statement, which is why there are two at the start of the condition.

Instructions

A cinema gives a discount to students and to people aged 65 or more. Write an if statement that prints Discount if isStudent is true or age is at least 65. Use ||.

New rule: discounts are only on Wednesdays. Add && day == "Wednesday" at the end of the condition, put the part with || in parentheses, and add an else branch that prints Full price. Today is Monday, so the program prints Full price.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

8/11