Thursday, April 14, 2011

c define 特殊字符 # ## #@ \

    偶然的机会读到酷壳的一篇关于语言的歧义的文章,对其中第四个puzzle印象颇深,不过印象更多是因为他说了一句“当然,你首先要了解##和#的用法,如果不懂的话,本题你可以直接跳过。”,我可以跳过了,但是肯定不甘心,果断去找##和#的用法,在Preprocessor directives中发现了#和##的定义,原文如下:

Function macro definitions accept two special operators (# and ##) in the replacement sequence:

If the operator # is used before a parameter is used in the replacement sequence, that parameter is replaced by a string literal (as if it were enclosed between double quotes)

1
2
#define str(x) #x
cout << str(test);
This would be translated into:
cout << "test";

The operator ## concatenates two arguments leaving no blank spaces between them:
1
2
#define glue(a,b) a ## b
glue(c,out) << "test";
This would also be translated into:
cout << "test";


#x表示给x加上双引号
x##y表示x连接y

    在查找特殊字符的同时,还发现了有的blog中提到了#@和\,比如你也许不知道的#define用法中就提到了:
#@x是给x加上单引号“'”
#define ToChar(x) #@x
char a = ToChar(1),就是a='1'

而\则很简单,类似于shell中的命令,可以用"\"表示下一行继续此宏的定义。

No comments:

Post a Comment