[英]Logical Operators and their precedence in C/C++
I was recently came across a piece of code 我最近遇到了一段代码
// Program to overcome division by zero //克服零除的程序
int a=0;
int b=100;
int c= a==0 || b/a ;
printf("Hello");
//Output : Hello //输出:你好
My theory: According to the precedence, operator / has higher precedence than ||. 我的理论:根据优先级,运算符/的优先级高于||。 So b/a must get executed first and we should get a run time error.
因此,b / a必须首先执行,我们应该遇到运行时错误。
I assume what is happening though is : 我认为发生的事情是:
short-circuit operator || 短路运算符|| , evaluates the LHS a==0, which is true and hence does not execute b/a.
,计算LHS a == 0,这是正确的,因此不执行b / a。
Is my theory wrong?. 我的理论错了吗? I am pretty sure this is something very simple that i just can't figure out right now
我很确定这是一件很简单的事,我现在不知道
Precedence doesn't imply evaluation order, only grouping (parentheses). 优先级并不意味着评估顺序,仅表示分组(括号)。
There is a sequence point (old parlance) after the evluation of the first operand of the ||
||
的第一个操作数确定之后有一个序列点(用旧的说法) , so the first operand of ||
,因此
||
的第一个操作数 must be evaluated before the second, regardless of what these operands are. 无论这些操作数是什么,都必须在第二个之前评估。 Since in this case the overall result of the expression
a == 0 || b/a
因为在这种情况下,表达式
a == 0 || b/a
的整体结果a == 0 || b/a
a == 0 || b/a
was determined by the first operand, the second isn't evaluated at all. a == 0 || b/a
由第一个操作数确定,而第二个则完全不评估。
The higher precedence of /
over ||
/
||
的较高优先级 means that the expression is evaluated as: 表示该表达式的计算结果为:
int c= (a==0) || (b/a) ;
And not 并不是
int c= (a==0 || b)/a ;
But still, as the logical evaluation is short-circuited, b/a
will only be evaluated if a!=0
. 但是仍然,由于逻辑评估被短路,只有当
a!=0
时才评估b/a
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.