#include <stdio.h>
void main()
{
int x = 1, y = 0, z = 5;
int a = x && y || z++;
printf("%d", z);
}
这会产生输出 6 而
#include <stdio.h>
void main()
{
int x = 1, y = 0, z = 5;
int a = x && y && z++;
printf("%d", z);
}
这会产生答案 5。为什么 ??有人请解释。
最佳答案
这是由于 Short Circuit mechanism .
这意味着当逻辑运算符的结果已经确定时,表达式的其余部分根本不会被计算,包括潜在的副作用。
第一个代码片段的行为如下:
int a = (1 && 0) /* result pending... */ || z++;
第二个:
int a = (1 && 0) /* result determined */;
发生这种情况是因为如果左侧表达式为假,则逻辑 AND 的值已知为假。
关于C 关系运算符输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34483871/