Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why adding bracket in If statements with Multiple AND OR gives different result?

I have simple program that has 1 AND and multiple OR operators as below :

#include <iostream>

using namespace std;

int main()
{
    bool a = true;
    bool b = true;
    bool c = true;
    bool d = true;

    if (!a && b || c || d)
        cout << "run";
    else
        cout << "pass";

    return 0;
}

I expect the program will output pass because I declare a as true. But, if you run the program it will give output : run

If I change the if statement line by adding bracket to

if (!a && (b || c || d))
        cout << "run";
    else
        cout << "pass";

It will give the expected output pass. Why does it work that way?

like image 837
gameon67 Avatar asked Dec 01 '22 13:12

gameon67


2 Answers

This is because the logical and operator (&&) has a higher precedence than the logical or operator (||), and the logical negation operator (!) has the highest precedence of the three.

This means that the expression !a && b || c || d is grouped as ((((!a) && b) || c) || d). Working from the inside out:

  • !a is false -> (((false && b) || c) || d)
  • false && b is false -> ((false || c) || d)
  • false || c is true -> (true || d)
  • true || d is true -> true

So the whole expression evaluates to true.

like image 70
Miles Budnek Avatar answered Dec 05 '22 02:12

Miles Budnek


The && operator has greater precedence than || in C++ (as well as the majority of other programming languages). So, your first version of the code was actually executing as if you had written this:

if ((!a && b) || c || d)  // if (false || true || true)
    cout << "run";
else
    cout << "pass";

Of course, the if statement passes as true, because both c and d were set to true at the start.

like image 33
Tim Biegeleisen Avatar answered Dec 05 '22 02:12

Tim Biegeleisen