C/C++宏定义中的## 连接符与# 符

##连接符号由两个井号组成,其功能是在带参数的宏定义中将两个子串(token)联接起来,从而形成一个新的子串。但它不可以是第一个或者最后一个子串。所谓的子串(token)就是指编译器能够识别的最小语法单元。具体的定义在编译原理里有详尽的解释,但不知道也无所谓。同时值得注意的是#符是把传递过来的参数当成字符串进行替代。下面来看看它们是怎样工作的。这是MSDN上的一个例子。

假设程序中已经定义了这样一个带参数的宏:

#define paster( n ) printf( “token” #n ” = %d”, token##n )
同时又定义了一个整形变量:

int token9 = 9;
现在在主程序中以下面的方式调用这个宏:

paster( 9 );
那么在编译时,上面的这句话被扩展为:

printf( “token” “9″ ” = %d”, token9 );
注意到在这个例子中,paster(9);中的这个”9”被原封不动的当成了一个字符串,与”token”连接在了一起,从而成为了token9。而#n也被”9”所替代。

可想而知,上面程序运行的结果就是在屏幕上打印出token9=9

26th June 2010 2 Comments Permalink

2 Comments

  1. 网赚资料 says:

    你的博客很不错,很欣赏你的博客,希望能交个朋友!

  2. 宝宝可儿 says:

    学了一下啦,这个地方不错,会常来看看的

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Statistical data collected by Statpress SEOlution (blogcraft).