Reputation: 73625
In what order are the following parameters tested (in C++)?
if (a || b && c)
{
}
I've just seen this code in our application and I hate it. I want to add some brackets to just clarify the ordering. But I don't want to add the brackets until I know I'm adding them in the right place.
C++ built-in operators, precedence, and associativity has more information, but it's not totally clear what it means. It seems || and && are the same precedence, and in that case, they are evaluated left-to-right.
Upvotes: 4
Views: 3545
Reputation: 41142
To answer the follow-up: obviously the table at MSDN is botched, perhaps by somebody unable to do a decent HTML table (or using a Microsoft tool to generate it!).
I suppose it should look more like the Wikipedia table referenced by Rodrigo, where we have clear sub-sections.
But clearly the accepted answer is right, somehow we have same priority with && and || than with * and +, for example.
The snippet you gave is clear and unambiguous for me, but I suppose adding parentheses wouldn't hurt either.
Upvotes: 0
Reputation: 1336
The page C++ Operator Precedence (found by googling "C++ operator precedence") tells us that &&
, in group 13, has higher precedence than ||
in group 14, so the expression is equivalent to a ||
(b && c
).
Unfortunately, the Wikipedia_ article Operators in C and C++, Operator precedence disagrees with this, but since I have the C89 standard on my desk and it agrees with the first site, I'm going to revise the Wikipedia article.
Upvotes: 7
Reputation: 3317
I'm not sure, but it should be easy for you to find out.
Just create a small program with a statement that prints out the truth value of:
(true || false && true
)
If the result is true, then the ||
has higher precedence than &&
, if it is false, it's the other way around.
Upvotes: -2
Reputation: 14961
&& (boolean AND) has higher precedence than || (boolean OR). Therefore the following are identical:
a || b && c
a || (b && c)
A good mnemonic rule is to remember that AND is like multiplication and OR is like addition. If we replace AND with * and OR with +, we get a more familiar equivalent:
a + b * c
a + (b * c)
Actually, in Boolean logic, AND and OR act similar to these arithmetic operators:
a b a AND b a * b a OR b a + b --------------------------------------- 0 0 0 0 0 0 0 1 0 0 1 1 1 0 0 0 1 1 1 1 1 1 1 1 (2 really, but we pretend it's 1)
Upvotes: 2