C++ 中的前缀增量预处理器
有人可以解释为什么 b = 150 吗?
#define CUBE(X) ((X) * (X) * (X))
using namespace std;
int main( void )
{
int a = 3,b = 0;
cout << "before "<< endl;
cout << "a = " << a;
cout << endl;
cout << "b = " << b;
cout << endl;
cout << "after"<< endl;
b = CUBE( ++a );
cout << "a = " << a;
cout << endl;
cout << "b = " << b;
getchar();
return 0;
}
Could somebody explain why b = 150 ?
#define CUBE(X) ((X) * (X) * (X))
using namespace std;
int main( void )
{
int a = 3,b = 0;
cout << "before "<< endl;
cout << "a = " << a;
cout << endl;
cout << "b = " << b;
cout << endl;
cout << "after"<< endl;
b = CUBE( ++a );
cout << "a = " << a;
cout << endl;
cout << "b = " << b;
getchar();
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
因为你使用的是宏。宏不是函数。
行:
被重写为:
在代码编译之前,
。 代码随后会调用未定义行为,因为您在序列点之间多次递增
a
。如果使用函数来代替会更好。
Because you're using a macro. Macros are not functions.
The line:
gets re-written as:
before your code compiles.
The code then invokes Undefined Behaviour because you increment
a
several times between sequence points.It would be better if you used a function instead.
(++a) * (++a) * (++a)
是(++a) * (++a) * (++a)
is undefined behaviour.未定义的行为 - 您在序列点之间多次修改
a
。这就是为什么内联函数是极其优越的选择。Undefined behaviour- you modify
a
more than once between sequence points. This is whyinline
functions are the vastly superior option.