前缀运算符在 C 中未按预期工作

Prefix operators are not working as expected in C

#include <stdio.h>
int main()
{
    int a = 1;
    int b = 1;
    int c = a || --b;
    int d = a-- && --b;
    printf("a=%d, b= %d, c= %d, d= %d",a,b,c,d);
    return 0;
}

在上面的代码中,我希望输出为 a=0, b= -1, c= 1, d= 0 但输出为 a=0, b= 0, c= 1, d= 0

Screenshot_VS Code

在此声明中用作初始值设定项的表达式中

int c = a || --b;

因为操作数 a 不等于 0,所以不计算表达式 --b

所以变量c1初始化。

来自 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.

在 tjis 声明中用作初始值设定项的表达式中

int d = a-- && --b;

操作数a--不等于0(后缀运算符的值为其操作数递减前的值)。所以操作数 --b 被评估。 由于其值等于 0,因此变量 d0.

初始化

来自 C 标准(6.5.13 逻辑与运算符)

4 Unlike the bitwise binary & 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 equal to 0, the second operand is not evaluated.

因此 ab 在此声明后将等于 0。