问题
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.
Edit: Accepted Answer & Follow Up
This link 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.
http://msdn.microsoft.com/en-us/library/126fe14k.aspx
回答1:
From here:
a || (b && c)
This is the default precedence.
回答2:
[http://www.cppreference.com/wiki/operator_precedence] (Found by googling "C++ operator precedence")
That page 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 [http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#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.
回答3:
&& (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)
回答4:
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.
回答5:
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 falase, it's the other way around.
来源:https://stackoverflow.com/questions/113992/c-binary-operators-order-of-precedence