Sri*_*mar 4 c logical-operators or-operator and-operator
#include <stdio.h>
void main()
{
int x = 1, y = 0, z = 5;
int a = x && y || z++;
printf("%d", z);
}
Run Code Online (Sandbox Code Playgroud)
这产生了6的输出
#include <stdio.h>
void main()
{
int x = 1, y = 0, z = 5;
int a = x && y && z++;
printf("%d", z);
}
Run Code Online (Sandbox Code Playgroud)
这会产生答案为5.为什么?有人请解释一下.
正如您可能知道的那样,两个代码片段之间的区别在于第一个评估z++,而另一个不评估。
第二个代码不求值的原因z++是它前面的表达式求值为false,因此&&链接“短路”最后一项的求值。
||另一方面,运算符仅当左侧为 时才会短路true。
这是由于短路机制造成的.
这意味着当已经确定逻辑运算符的结果时,根本不评估表达式的其余部分,包括潜在的副作用.
第一个代码片段的行为如下:
int a = (1 && 0) /* result pending... */ || z++;
Run Code Online (Sandbox Code Playgroud)
第二个:
int a = (1 && 0) /* result determined */;
Run Code Online (Sandbox Code Playgroud)
发生这种情况是因为如果左侧表达式为false,则逻辑AND的值已知为false.