C++ Binary operators order of precedence

感情迁移 提交于 2019-12-04 12:19:52
tzot

From here:

a || (b && c)

This is the default precedence.

[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.

&& (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)

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!