问题描述
因此,我正在编写一些代码,并且在程序的一部分中得到了意外的输出,这破坏了整个系统.
So, I was writing some code and I was getting an unexpected output in one part of my program which disrupted the entire system.
我设法将问题提取并简化为基本的逻辑表达式.假设:
I managed to extract and simplify the problem to a basic logical expression. Let's say:
int i = 1, j = 1, k = 0;
printf("%d\n", ++i || ++j && k);
printf("%d, %d, %d\n", i, j, k);
return 0;
该程序的输出为:
1
2
1
0
我认为由于||
运算符的短路特性,j
的值未增加到2
.但是我很困惑第一个"%d"
的值是1
.对于&&
语句返回1
来说,k
的值是否不应该为非零?还是因为++i || ++j
不是0
并因此返回1
而根本不执行该语句?
I am thinking that the value of j
was not incremented to 2
due to the short circuit nature of the ||
operator. However I am confused how the value of the first "%d"
is 1
. Shouldn't the value of k
be non-zero for the &&
statement to return 1
? Or isn't this statement executed at all since ++i || ++j
is not 0
and thus returns a 1
?
- 我知道
&&
是逻辑和,而 expr1 &&如果 expr1 &&的值为 expr2 ,则其值为1. expr2 均为两者非零.
- I know that
&&
is a logical and, and expr1 && expr2 has the value 1 if values of expr1 && expr2 are both non-zero.
任何澄清将不胜感激,请原谅此问题的基本性质.
Any clarifications would be appreciated and please excuse the basic nature of this question.
推荐答案
&&
的优先级高于||
.(请参见 https://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B)所以
&&
has higher precedence than ||
.(See https://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B )so
++i || ++j && k
是
++i || (++j && k)
如果和||
会短路> 6.5.14p4 .
and ||
shortcircuits if the first operator is truthy, as per 6.5.14p4 .
如果您使用的是gcc
或clang
,并使用-Wall
编译代码,则编译器会轻推您将这些括号放在此处.听取建议可能是一个好主意,因为有些人对优先顺序感到困惑(我听到).
If you're on gcc
or clang
and compile your code with -Wall
, the compiler will nudge you to put those parentheses there. It's probably a good idea to heed that advice, as some people get confused by the precedences (I hear).
这篇关于C误解中的逻辑表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!