解释逻辑

Explain the logic

  #include <stdio.h>
 //Compiler version gcc 6.3.0

 int main(void)
 {
    int i=10, j=2, k=0, m;
    m=++i || ++j && ++k;
    printf("%d,%d,%d,%d",i,j,k,m);
 }

can anyone explain the logic, Output is 11,2,0,1

i 开始时为 10,但在测试之前增加到 11。

m 被分配了一个布尔结果,因此将是 0 或 1。

i 不为零,因此布尔表达式的计算结果为真,因此,|| 之后的表达式不需要评估,因为 ||是布尔短路求值器。

因此你的输出。

由于此表达式语句的操作优先级

m=++i || ++j && ++k;

等同于

m = ++i || ( ++j && ++k );

你可以这样想象

m = expression1 || expression2;

其中 expression1++iexpression2( ++j && ++k )

根据 C 标准(6.5.14 逻辑或运算符)

4 Unlike the bitwise | operator, the || operator guarantees left-to-right evaluation; if the second operand is evaluated, there is a sequence point between the evaluations of the first and second operands. If the first operand compares unequal to 0, the second operand is not evaluated.

由于 expression1 比较不等于 0(其值等于 11),因此 expression2 不被评估。

因此只有 expression1 被评估,它不等于 0。

根据 C 标准同一部分的另一引述

3 The || operator shall yield 1 if either of its operands compare unequal to 0; otherwise, it yields 0. The result has type int.

右边的求值结果等于赋值给变量m的1。

因此只有变量 im 被改变了。变量 jk 未更改,因为它们作为操作数存在的表达式未被计算。