Boolean equation

Why this fragment of code has two different outputs (GCC 4.5.1) (I've commented important lines):

int main()
{
    bool a = 1;
    bool b = 1;
    bool c = 1;
    bool a_or_b = (a || b);
    bool not_a_or_b = !a_or_b;
    bool not_a_or_b__c = not_a_or_b || c;
    cout << "(a || b): " << (a || b) << '\n';
    cout << "!(a || b): " << !(a || b) << '\n';
    cout << "!(a || b) || c: " << (!(a || b)) || c << '\n';//HERE I'M GETTING 0 (incorrectly I would say)
    cout << "bool vars:\n";//WHY THIS LINE IS PRINTED AFTER THE PREVIOUS LINE BUT NOT BELOW IT?
    cout << "(a || b): " << a_or_b << '\n';
    cout << "!(a || b): " << not_a_or_b << '\n';
    cout << "!(a || b) || c: " << not_a_or_b__c << '\n';//HERE I'M GETTING 1
    return 0;
}

Upvotes: 1

Views: 366

Answers (4)

Daniel
Daniel

Reputation: 49

Is this a Clamp Issue

u use (!(a || b)) || c the first part is 0 for sure perhaps the interpreter doesnt even watch the || c part.

Upvotes: 0

Sjoerd
Sjoerd

Reputation: 75578

It interprets

(!(a || b)) || c << '\n'

as

(!(a || b)) || (c << '\n')

Upvotes: 4

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361252

Change this part:

<< (!(a || b)) || c << '\n'; //interpreted as (!(a || b)) || (c << '\n')

to this:

((!(a || b)) || c) << '\n'; //interpreted as intended!

Upvotes: 2

kennytm
kennytm

Reputation: 523164

This is because << has higher precedence than ||. Use parenthesis to group it.

cout << "!(a || b) || c: " << ((!(a || b)) || c) << '\n';
//                            ^                ^

Upvotes: 12

Related Questions