gpt4 book ai didi

c - 为什么 j 在 (++i ||++j) 中不递增

转载 作者:行者123 更新时间:2023-12-02 06:13:48 24 4
gpt4 key购买 nike

我不明白这段代码的输出:

 long i=5, j=10;
if (++i || ++j) printf("%ld %ld\n", i, j);
else printf("Prog1\n");

输出是 6 和 10。我期望是 6 和 11。为什么 j 没有递增?

最佳答案

逻辑或运算符 || 是一个 short circut operator .这意味着如果仅通过查看左操作数即可确定结果,则不会评估右操作数。

C standard 的第 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.

在这种情况下,++i 被评估,结果为 6(具​​有递增 i 的副作用。逻辑 OR 运算符评估为 1(即 true ) 如果任一操作数不为零。由于左侧不为零,因此不计算右侧,随后 j 不递增。

关于c - 为什么 j 在 (++i ||++j) 中不递增,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49521711/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com