复杂 if 条件
在遗留代码中,我遇到了以下表达式:
if (!m_bMsOcs && bChannelData || m_bMsOcs && !bStunType)
我猜预期的条件是
if ((!m_bMsOcs && bChannelData) || (m_bMsOcs && !bStunType))
我不确定。原始条件表达式应该如何执行?请帮忙。
In a legacy code, I have encountered the following expression:
if (!m_bMsOcs && bChannelData || m_bMsOcs && !bStunType)
I guess the intended condition was
if ((!m_bMsOcs && bChannelData) || (m_bMsOcs && !bStunType))
I am not sure. How is the original conditional expression supposed to execute? Please help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
逻辑运算符的优先级是:
所以你的猜测是正确的。
The precedence of logical operators is:
so your guess is correct.
运算符优先级为
!
>&&
> <代码>||The operator precedence is
!
>&&
>||
这是一个运算符优先级问题。括号优先,然后是逻辑。作为&&比 || 具有更高的优先级,你的猜测是正确的。
This is an operator precedence question. The parenthesis take precedence, followed by your logicals. As && has greater priority than ||, you're correct in your guess.
逻辑
and
的优先级高于or
:link所以你的逻辑是正确的。
Logical
and
have higher precedence thanor
: linkSo you are right about the logic.
你自己的答案是正确的:)
如果(这个和那个)或(这个和那个)
所以如果其中一个和是正确的,它的评估结果为真
Your own answer is correct:)
If (this and that) or (this and that)
So if either of the ands are correct it evaluates true
正如其他人所说,由于 C++ 优先级规则,这两个表达式是等效的。
这是一个真值表,可能有助于弄清楚会发生什么(我同意条件表达式也比我喜欢的更复杂):
请注意
1
和0
表中仅表示true
/false
值(即,变量的值不必为1
- 任何非零值将被视为1
)。我只是发现使用0
/1
而不是T
/F
使表格更具可读性。As others have said, the two expressions are equivalent because of C++ precedence rules.
Here's a truth table that might help make it clear what will happen (I agree that the conditional expression is more complex than I like, too):
Note that the
1
and0
in the table just representtrue
/false
values (i.e., the variables don't have to have a value of1
- any non-zero value will be treated as a1
). I just find the table to be more readable using0
/1
instead ofT
/F
.