新浪博客

C语言宏定义#define时,#(井号)和##(双井号)的用法

2018-09-28 21:11阅读:
1. #:在宏展开的时候会将#后面的参数替换成字符串
#define p(exp) printf(#exp);
调用p(test)的时候会将#exp换成'test'
2. ##:将前后两个的单词拼接在一起
#define cat(x,y) x##y
调用cat(var, 123)展开后成为var123
3. #@:将值序列变为一个字符
#define ch(c) #@c
调用ch(a)展开后成为'a'
举例如下:
C++ Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23


#include
void quit_command(){
printf(
'I am quit command');
}
void help_command(){
printf(
'I am help command');
}
struct command
{
char * name;
void (*function) (void);
};
#define COMMAND(NAME) {#NAME,NAME##_command}
#define PRINT(NAME) printf('token'#NAME'=%d', token##NAME)
main(){
int token9=9;
PRINT(
9);
struct command commands[] = {
COMMAND(quit),
COMMAND(help),
};
commands[
0].function();
}


【例子中】
#define PRINT(NAME) printf('token'#NAME'=%d', token##NAME)
调用时候使用:PRINT(9);
即为:printf('token'#9'=%d',token##9);
#9即为'9',token##9即为:token9
整个为:printf('token''9''=%d',token9);
之前定义过token9为9,所以就是输出token9=9

我的更多文章

下载客户端阅读体验更佳

APP专享