这个程序的输出是什么

时间:2014-08-06 09:02:54

标签: c

请解释此计划的输出。

#include<stdio.h>

int main()
{
    int x=0;
    x ^= x || x++ || ++x || x++;

    printf("\n%d",x);
}

O / p为3(http://codepad.org/X49j0etz

According to me output should be 2.
as || is a sequence point as far as i remember.
so expression becomes.

x ^= 0 || 0 || 2 || 2;

so after evaluation of this expression(x || x++ || ++x || x++;) x becomes 3
x  = 3 ^ 1
so x becomes 2;

2 个答案:

答案 0 :(得分:2)

我非常确定声称未定义行为的答案是正确的,但也有一个简单的解释,说明如何得出3的结果。

考虑到最后的x++永远不会被评估,因为最后||个操作会短路,并且假设在评估^ =之前应用了副作用。然后你就离开了

x = 2 ^ 1;

不出所料导致3。

答案 1 :(得分:0)

这是c中的未定义行为。因为我们无法预测表达式的评估方向