gpt4 book ai didi

c - 是 'if'条件下被忽略的运算符的优先级

转载 作者:太空狗 更新时间:2023-10-29 17:07:17 25 4
gpt4 key购买 nike

我有以下代码:

void main()
{
int k, x, y, z;
printf("\nExperiment 1:");
x = 0, y = 0, z = 0;
k = x++ || y++ && z++;
printf("\nx = %d, y = %d, z = %d and k = %d\n", x, y, z, k);
printf("\nExperiment 2:");
x = 1, y = 0, z = 0;
k = x++ || y++ && z++;
printf("\nx = %d, y = %d, z = %d and k = %d\n", x, y, z, k);
}

输出:

实验一:x = 1, y = 1, z = 0 和 k = 0

实验二:x = 2, y = 0, z = 0 和 k = 1

我的理解是:要使表达式为真,'||' 的左侧或右侧必须是非零的。它从左边开始。如果 left 不为零,则不会进一步评估。如果为零,则从右侧开始。在右边我们有'&&'。因此,我们再次从 && 的左侧开始,如果它为零,则表达式不可能为真并且不会继续。否则它计算'&&'的右边

我的假设是运算符 && 具有更高的优先级。因此,它的两个参数都应该被评估,然后 && 应该被应用于它,然后对 || 的两个参数进行评估。

编译器是否在优化自身?我使用了禁用优化的 Visual Studio TC 编译器。

最佳答案

我认为这在 C11 中由 §6.5.14 逻辑或运算符(我的重点)涵盖

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.

关于c - 是 'if'条件下被忽略的运算符的优先级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16608439/

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