#include <iostream>
#define DOUBLE1(x) x + x
#define DOUBLE2(x) 2 * x
int main() {
int a = 2;
std::cout << DOUBLE2(a++) << " " << DOUBLE1(++a) << std::endl;
std::cout << a;
}
该程序的执行会在
4 9 5
中打印 clang++
,并在 4 10 5
中打印 g++
。
我对操作优先级如何发生感到困惑。
注意: 我没有编写此代码,这是课程中作为
predict output question
提出的要求。
你的课程应该教你这样的东西:
#include <iostream>
// Macros are a last resort
// and usually only used when
// you need to concatenate some strings to
// make new lines of code
//#define DOUBLE1(x) x + x
//#define DOUBLE2(x) 2 * x
int double1(int a)
{
return a+a;
}
int double2(int a)
{
return 2*a;
}
int main() {
int a = 2;
// epxlicitly model evaluation order
// the compiler will not care you write
// extra lines. It will still create
// good (optimized) assembly code.
// and at least now you can set breakpoints
// to check what your code is doing in a debugger
int a2 = double2(a);
a++;
++a;
int a3 = double1(a);
std::cout << a2 << " " << a3 << "\n"; //std::endl; only use endl when you need to flush
std::cout << a;
}