Chinaunix首页 | 论坛 | 博客
  • 博客访问: 20164
  • 博文数量: 8
  • 博客积分: 306
  • 博客等级: 二等列兵
  • 技术积分: 110
  • 用 户 组: 普通用户
  • 注册时间: 2012-03-17 09:21
文章分类
文章存档

2012年(8)

我的朋友

分类: C/C++

2012-03-18 06:05:02

在linux kernel中有下面这样一个宏:
/**
 * container_of - cast a member of a structure out to the containing structure
 * @ptr: the pointer to the member.
 * @type: the type of the container struct this is embedded in.
 * @member: the name of the member within the struct.
 *
 */
#define container_of(ptr, type, member) ({   \
 const typeof(((type *)0)->member) * __mptr = (ptr); \
 (type *)((char *)__mptr - offsetof(type, member)); })
 
不管宏的功能,发现在记号序列中出现了形参以外的标号(不知道能否称作变量...)“__mptr”,看起来像是声明了__mptr,然后在下面的语句中使用。
预处理器对宏执行的是替换操作,那么以上语句中“__mptr”的声明和操作语句在预处理阶段会被替换到对应宏标记处。这样看起来“__mptr”和其它变量的声明过程没有任何区别了,也就是说在宏里面声明的变量当宏在某函数使用时就相当于函数的局部变量??如果是这样,那么有个结论:“可以用宏进行变量声明(至少在函数中可以)”??
为此,在linux,gcc编译器环境下做如下试验:
代码():
#define AAA(x) ({ \
        int b;\
        b = x;\
        b;\
})
int main(int argc, char *argv[])
{
        int a = 0, c = -1;
        c = AAA(a);
        return 0;
}
预处理结果:
int main(int argc, char *argv[])
{
        int a = 0, c = -1;
        c = ({int b; b = a; b; });
        return 0;
}
 
宏只进行特定的文本处理,而不关心内容的含义。
阅读(2519) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~