gpt4 book ai didi

c - C语言中的短路评估是什么?

转载 作者:行者123 更新时间:2023-11-30 16:09:53 25 4
gpt4 key购买 nike

我正在从 Kelley-Pohl 的《A Book on C》中学习 C,但有一个练习我不明白:

int a = 0, b = 0, x;

x = 0 && (a = b = 777);
printf("%d %d %d\n", a, b, x);
x = 777 || (a = ++b);
printf("%d %d %d\n", a, b, x);

他们只是说想象输出并将其与真实输出进行比较。我以为输出会是

777 777 0

778 778 1

但确实如此

0 0 0

0 0 1

最佳答案

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

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

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.

在此表达式语句中

x = 0 && (a = b = 777);

第一个操作数比较等于 0。因此第二个操作数不会被求值,即变量 ab 的值没有改变。因此,根据本节的第 #3 段,变量 x 将被设置为 0

来自 C 标准(6.5.14 逻辑 OR 运算符)

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

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.

在此表达式语句中

x = 777 || (a = ++b);

第一个操作数与 0 比较不等于。因此第二个操作数未计算,即变量 ab 的值未更改。因此变量根据本节第 3 段,x 将设置为 1

如果您要更改表达式中操作数的顺序,例如

x = (a = b = 777) && 0;
x = (a = ++b) || 777;

您得到了预期的结果。

关于c - C语言中的短路评估是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58999415/

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