有人可以向我解释这里发生了什么吗?
我有这行代码:
if ( pt->child == NULL && pt->visits < cutoff+1 || depth > 5 )
我正在收到 g ++编译器警告:
warning: suggest parentheses around ‘&&’ within ‘||’ [-Wparentheses]|
它试图警告我什么?更糟糕的是,如果我加入“明显的”parens,就像这样:
if ( ( pt->child == NULL && pt->visits < cutoff+1 ) || depth > 5 )
我得到了一个不同的行为 - 表明我在第一个表达式中确实做错了。算术运算符优先于比例优先于布尔运算符的优先级,其中&&
的优先级高于||
,对吧?
我错过了什么?
答案 0 :(得分:0)
就像数字运算符+和*一样,逻辑运算符具有不同的优先级。因此,逻辑陈述的评估顺序不一定是严格从左到右,而是评估&amp;&amp;首先和||第2位。这是混淆和错误的根源,编译器会发出此警告,除非您明确用括号括起元素。
这里发生了什么?我认为在这种情况下它是错误的,因为如果你让g ++转储它的内部结构
此
if ( pt->child == NULL && pt->visits < cutoff+1 || depth > 5 )
printf("Hello World");
等同于此
D.3367 = pt->child;
if (D.3367 == 0B) goto <D.3368>; else goto <D.3364>;
<D.3368>:
D.3369 = pt->visits;
D.3370 = cutoff + 1;
if (D.3369 < D.3370) goto <D.3365>; else goto <D.3364>;
<D.3364>:
if (depth > 5) goto <D.3365>; else goto <D.3366>;
<D.3365>:
printf ("Hello World");
<D.3366>:
这正是你所期望的。