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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With