首页
社区
课程
招聘
谁能说清C语言中宏的替换规则?进来看看
发表于: 2006-11-10 16:56 5995

谁能说清C语言中宏的替换规则?进来看看

2006-11-10 16:56
5995
先看这个例子:

#define hash_hash # ## #
#define mkstr(a) # a
#define in_between(a) mkstr(a)
#define join(c, d) in_between(c hash_hash d)
char p[] = join(x, y); // equivalent to
                       // char p[] = "x ## y";

替换过程分步走如下:

第一步:join(x, y)
第二步:in_between(x hash_hash y)
第三步:in_between(x ## y)
第四步:mkstr(x ## y)
结果:  "x ## y"

看完以上的例子谁能说清下面的问题?

#define B A+C
#define C B+A
#define A B+C

A;
上面的A将会被扩展为什么?如果扩展中途出错,它是在执行哪一步时出错的?
如果谁能给出通用的替换法则,则最好!

看雪尽是高手,虽此题与调试关系不大,特来求个答案!

[培训]内核驱动高级班,冲击BAT一流互联网大厂工作,每周日13:00-18:00直播授课

收藏
免费 0
支持
分享
最新回复 (7)
雪    币: 125
活跃值: (10)
能力值: ( LV2,RANK:10 )
在线值:
发帖
回帖
粉丝
2
的确好难..
2006-11-10 22:57
0
雪    币: 1852
活跃值: (504)
能力值: (RANK:1010 )
在线值:
发帖
回帖
粉丝
3
你的标题我已经编辑过了。
2006-11-11 09:03
0
雪    币: 1852
活跃值: (504)
能力值: (RANK:1010 )
在线值:
发帖
回帖
粉丝
4

#define B A+C
#define C B+A
#define A B+C


嵌套定义出现循环。替换的时候,出现死循环。
2006-11-11 09:17
0
雪    币: 5008
活跃值: (1147)
能力值: ( LV2,RANK:10 )
在线值:
发帖
回帖
粉丝
5
都是高手,学习
我想也是死循环吧
如果要搞懂哪一步出现问题,是不是应该看C语言#define编译的定义啊?
2006-11-11 10:26
0
雪    币: 267
活跃值: (16)
能力值: ( LV4,RANK:50 )
在线值:
发帖
回帖
粉丝
6
首先,宏里的参数表是不能替换的
============
#define B A+C
#define C B+A
#define A B+C

A;
============
#define B A+C
#define C B+A
#define A B+C

B+C;
============
#define B A+C
#define C B+A
#define A B+C

A+C+B+A;
============
#define B A+C
#define C B+A
#define A B+C

A+B+A+A+C+A;
============
标准里有这么写:
If the name of the macro being replaced is found during this scan of the replacement list
(not including the rest of the source file’s preprocessing tokens), it is not replaced.
Furthermore, if any nested replacements encounter the name of the macro being replaced,
it is not replaced. These nonreplaced macro name preprocessing tokens are no longer
available for further replacement even if they are later (re)examined in contexts in which
that macro name preprocessing token would otherwise have been replaced.
也就是说只能替换一次,在第三步里虽然又出现了A,但它是不可替换的
2006-11-11 11:53
0
雪    币: 229
活跃值: (168)
能力值: ( LV8,RANK:130 )
在线值:
发帖
回帖
粉丝
7
确实是高手!佩服佩服!
感谢!
2006-11-13 10:34
0
雪    币: 207
活跃值: (10)
能力值: ( LV2,RANK:10 )
在线值:
发帖
回帖
粉丝
8
最初由 Rinrin 发布
首先,宏里的参数表是不能替换的
============
If the name of the macro being replaced is found during this scan of the replacement list
(not including the rest of the source file’s preprocessing tokens), it is not replaced.
Furthermore, if any nested replacements encounter the name of the macro being replaced,
it is not replaced. These nonreplaced macro name preprocessing tokens are no longer
available for further replacement even if they are later (re)examined in contexts in which
that macro name preprocessing token would otherwise have been replaced.

........


6楼老兄说的不错呀。。。。。但大家可能没有想到宏如果嵌套定义。。。就像上面那样。。是跟本行的。。。会出没有使用的符号没有写义的错误哦。。。这只是我个人的看法。。。。。
2006-11-13 11:49
0
游客
登录 | 注册 方可回帖
返回
//