问题描述
我正在做一些复习题,问我以下内容的输出是什么",并且在理解有关此功能的内容时遇到了一些麻烦:
I am doing review questions which ask me "What is the output of the following," and I am having some trouble understanding something about this function:
int a = 1, b = 1, c = -1;
c = --a && b++;
printf("%d %d %d", a, b, c);
输出是010.我的问题是关于第2行,c = --a && b++
.这条线是如何处理的,以及它如何工作/更改值?如果是c = --a || b++
?根据我的理解,我认为输出为020.
The output is 010. My question is about line 2, c = --a && b++
. How is this line processed, and how does it work/change the values? And if it were c = --a || b++
? From my understanding I thought the output would be 020.
推荐答案
理解结果的关键概念是布尔运算符(&&
和||
)的短路评估-如果在评估布尔运算符的左侧后,如果右侧的值不能影响整个结果,那么就不会对其进行评估,并且不会产生任何副作用.
The key concept to understanding the result is short-circuit evaluation of Boolean operators (&&
and ||
) -- if, after evaluating the left-hand side of a Boolean operator, the value of the right-hand side cannot affect the overall result, then it will not be evaluated and any side-effects it would produce will not happen.
在第一种情况下,由于--a
评估为0
(= false),因此不评估... && ...
的第二部分,因为" false AND any "将始终为false.具体来说,b++
不会执行,因此其值在输出中仍为1
.
In the first case, since --a
evaluates to 0
(=false) the second part of ... && ...
is not evaluated, since "false AND anything" will always be false. Specifically, b++
is never executed, and so its value remains 1
in the output.
在--a || b++
的情况下,整个表达式 的值不能由左侧确定(" false或某物"仍然为true ),因此对b++
进行了评估(并且副作用是,增加b
会发生).
In the case of --a || b++
, the value of the whole expression cannot be determined by the left-hand side ("false OR something" can still be true) so the b++
is evaluated (and it's side-effect, incrementing b
, happens).
完全了解结果所需的另一个概念是前后递增/递减运算符之间的差异.如果--
或++
出现在变量之前(如--a
中所示),则变量将先减小或增大,然后使用 new 值评估变量的值.整个表情.如果--
或++
出现在变量后 (如b++
),则该变量的 current 值将用于计算表达式和增量/递减发生在这种情况发生之后.
The other concept needed to fully understand the results is the difference between pre- and post-increment/decrement operators. If the --
or ++
appears before the variable (as in --a
) then the variable is decremented or incremented first and new value is used to evaluate the whole expression. If the --
or ++
appears after the variable (as in b++
) then the current value of the variable is used to evaluate the expression and the increment/decrement happens after this has happened.
应注意,试图合并同一变量的--
/++
的两个或多个实例(例如a++ + ++a
)的表达式很可能会调用不确定的行为-结果可能因平台,编译器,编译器甚至一天中的时间而异.
It should be noted that expressions that try to combine two or more instances of --
/++
of the same variable (e.g. a++ + ++a
) are quite likely to invoke undefined behaviour -- the result may vary by platform, compiler, compiler and even the time of day.
这篇关于该函数输出的说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!