看下面这段代码,你猜输出的结果是什么?
#include <iostream>
using namespace std;
void fun(int a, int b) {
cout << a << "," << b << endl;
}
int main(){
int x = 0;
fun(x=x+1, x=x+1);
}
实际运行结果却是根据编译器的不同而不同!
1. 使用mac自带的clang++编译器,结果是1,2
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/4.2.1
Apple clang version 13.0.0 (clang-1300.0.29.30)
Target: arm64-apple-darwin21.1.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
2. 使用g++的结果是2,2
为何会出现这种不确定性?
其实这是因为C++或者C语言在执行同一优先级的语句时,不同的编译器采用了不同的指令执行方式。fun()函数内部的两个表达式x=x+1是处于同一优先级,gcc这种编译器为了追求效率,会采用乱序的方式执行这两个表达式,因此x的值不好确定是哪个先求,因此同时得到了x=2这个结果。
而clang++这给出了相应的警告信息,然后按照从左往右的方式顺序执行。
warning: multiple unsequenced modifications to 'x' [-Wunsequenced]
fun(x=x+1, x=x+1);
总体而言,clang++的执行方式更符合我们的主管理解,但仍然要避免写出这种不确定性结果的语句。