我不了解C ++中#define宏的行为 [英] I do not understand the behaviour of #define macro in C++

查看:87
本文介绍了我不了解C ++中#define宏的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要了解这段代码的工作原理:

I need to understand how this code works:

#define foo1( a ) (a * a)              // How does this work?
inline int foo2( int a ) { return (a * a); }
int goo1( int x ) { return foo1(foo2(x)); }
int goo2( int& x ) { return x = foo2(foo1(x)); }
int goo3( int& x, int y ) { return foo2(foo1(y + 1)); }
void goo4( int& x, int y ) { x = foo1(foo2(y + 1)); }

int main(){
int i = 2, j = 1, a = 2+3;

cout << "foo1 = " << foo1( 1+2 ) << "\n";  // How does this work?
cout << "foo2 = " << foo2( 2 + 1 ) << "\n";
cout << "goo1 = " << goo1( i ) << "\n";
cout << "goo2 = " << goo2( j ) << "\n";
cout << "goo3 = " << goo3( i, j ) << "\n";  // How does this work?
goo4( i, j );
cout << " i = " << i << " j = " << j << "\n";
}

但是我似乎无法理解此功能的行为:

But I do not seem to be able understand the behaviour of this function:

#define foo1( a ) (a * a)

,因此我不理解这两个函数调用的输出:

and hence I don't understand the output of these two function calls:

foo1( 1+2 )
goo3( i, j )

这是程序的输出:

foo1 = 5
foo2 = 9
goo1 = 16
goo2 = 1
goo3 = 9
 i = 16 j = 1

我不明白为什么foo1的行为不像foo2那样.有人会告诉我这个#define宏的工作原理吗?

I can't see why foo1 is not behaving like foo2. Would someone explain to me how this #define macro works?

注意:我不能更改代码,我只是想了解输出.

NOTE: I must not change the code, I am only trying to understand the output.

推荐答案

宏不是函数.

宏可以进行TEXT替换.所以当你有

Macros do TEXT replacement. So when you have

#define foo1( a )   (a * a)

foo1( ... )的任何实例,括号之间的任何内容都将扩展为AS TEXT,而不作为表达式.因此,当您拥有foo1( 1 + 2 )时,它会变成( 1 + 2 * 1 + 2 )

any instance of foo1( ... ) with anything between then parenthesis will be expanded AS TEXT, not as an expression. So when you have foo1( 1 + 2 ) it turns into ( 1 + 2 * 1 + 2 )

这篇关于我不了解C ++中#define宏的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆