Different Execution Sequences of Multiple Function Calls As Function Parameters
Problem
The execution sequence of multiple function calls that are used as function parameters is not defined, which may cause dependency problems. In the following example, the binary execution sequence of BiSheng compiler is different from that of the GNU compiler.
#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 |
Solution
- Replace function parameters with temporary variables.
- Use the clang-tidy tool to identify such issues and provide modification suggestions.
Parent topic: Other Compatibility Problems