#include <stdio.h>
void main()
{
int x= 1;
printf("%d %d %d ", x, (x = x + 2), (x << 2));
x << 2;
printf("%d %d %d \n", x++, ++x, ++x);
}
在 XCode 和 gcc 中都尝试过:
XCode 输出:1 3 12 3 5 6
海湾合作委员会输出:3 3 4 5 6 6
(正确输出)
为什么 XCode 输出出错?
最佳答案
函数参数的求值顺序为 unspecified behavior在C语言中。两个输出都是正确的,因为这是特定编译器决定实现它的方式。您的程序是“错误的”,因为它没有通过使用中间值来保证顺序来正确处理这种未指定的行为。
该程序使用两个编译器产生相同的结果 (3 3 4 4 5 5
)
#include <stdio.h>
int main() {
int x = 1;
int y = x;
x = x + 2;
printf("%d %d %d ", x, x, (y << 2));
int value1 = x++;
int value2 = ++value1;
int value3 = ++value2;
printf("%d %d %d \n", value1, value2, value3);
return 0;
}
Clang 实际上默认提供了一个有用的警告来避免这种情况:
warning: unsequenced modification and access to 'x' [-Wunsequenced]
printf("%d %d %d ", x, (x = x + 2), (x << 2));
~ ^
关于c - 以下代码中 XCode 输出和 gcc 输出之间差异如此之大的原因是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46099249/