多个作为函数参数的函数调用执行顺序存在差异
问题介绍
多个作为函数参数的函数调用,执行顺序是未定义的,可能会造成依赖问题。在以下例子中,毕昇与GNU编译的二进制执行顺序有差异:
#include <iostream>
int global_value = 0;
int f1() {
global_value += 10;
std::cout << "f1 called, global_value=" << global_value << std::endl;
return 1;
}
int f2() {
global_value *= 2;
std::cout << "f2 called, global_value=" << global_value << std::endl;
return 2;
}
int add(int a, int b) {
return b;
}
int main() {
int b = add(f1(), f2());
return 0;
}
1 2 3 4 5 6 | $ clang++ test.cpp && ./a.out f1 called, global_value=10 f2 called, global_value=20 $ g++ test.cpp && ./a.out(X86平台) f2 called, global_value=0 f1 called, global_value=10 |
解决方案
- 将函数参数用临时变量替换;
- 使用clang-tidy工具可以识别该类问题并提供修改建议。
父主题: 其它类兼容问题