简体   繁体   English

C ++运算符优先级

[英]C++ operators precedence

I am using this statement 我正在使用此语句

if ((pm && pn) || (pm == false && pn == false))

it is supposed to return true only if both pm and pn are true or if both are false. 仅当pm和pn均为true或均为false时,才应返回true。 But this is also returning true if only only first one (pm) is true. 但是,如果只有第一个(pm)为真,则这也返回true。

So now it is acting like this: 所以现在它的行为是这样的:

0 0 = 1
0 1 = 0
1 0 = 1
1 1 = 1

but I need it to work like this: 但我需要它像这样工作:

0 0 = 1
0 1 = 0
1 0 = 0
1 1 = 1

can you tell me where am I making mistake? 你能告诉我我在哪里犯错吗?

您想要的只是:

if (pm == pn)

You are checking if pm is true twice. 您正在检查pm是否为真两次。 You also need to check if both are the same, not whether they are both true. 您还需要检查两者是否相同,而不是两者都正确。 So, 所以,

if ((pm == pn) 
        ^^ ^^
pm && pm

should be 应该

pm && pn
       ^

The whole expression can be simplified to 整个表达式可以简化为

pm == pn

if the variables already have bool type. 如果变量已经具有bool类型。

Why not try xor? 为什么不尝试xor?

if (!(pm ^ pn)) { /*...*/ }

Or simply equal? 还是简单相等?

if (pm == pn) { /*...*/ }
 if ((pm && pm) || (pm == false && pn == false)) 

it is supposed to return true only if both pm and pn are true or if both are false. 仅当pm和pn均为true或均为false时,才应返回true。 But this is also returning true if only only first one (pm) is true. 但是,如果只有第一个(pm)为真,则这也返回true。

Because you made a typo. 因为你打错字了。 You meant pm && pn . 您的意思是pm && pn

Instead just write if (pm == pn) , which is equivalent along as the only semantic values are indeed true and false for both variables. 而是只写if (pm == pn) ,这与两个变量的唯一语义值确实为truefalse

Plus, consider making your variable names clearer and more distinct. 另外,请考虑使您的变量名称更清晰,更独特。

Note that operator precedence has nothing to do with this. 请注意,运算符优先级与此无关。

Since the question's title asks about precedence, note that || 由于问题的标题询问优先级,请注意|| has lower precedence than && . 优先级低于&& So the two sets of inner parentheses are redundant, and the original expression is just a longer way of saying 因此,两组内部括号是多余的,原始表达式只是一个较长的说法

if (pm && pm || pm == false && pn == false)

Now, fixing the obvious typo: 现在,修复明显的拼写错误:

if (pm && pn || pm == false && pn == false)

Removing the unneeded explicit comparisons: 删除不需要的显式比较:

if (pm && pn || !pm && !pn)

And, finally, a less obvious transformation, which others have suggested: 最后,还有一个不太明显的转换,其他人建议:

if (pm == pn)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM