c - 为什么我们需要在 block 宏周围加上括号?

标签 c gcc linux-kernel

在 linux 中,container_of 宏包含在看似“额外”的括号中:

 #define container_of(ptr, type, member) ({ \
                const typeof( ((type *)0)->member ) *__mptr = (ptr); 
                (type *)( (char *)__mptr - offsetof(type,member) );})

我们能不能用它来代替

 #define container_of(ptr, type, member) { \
                const typeof( ((type *)0)->member ) *__mptr = (ptr); 
                (type *)( (char *)__mptr - offsetof(type,member) );}

?

括号是强制性的还是只是为了预防?

最佳答案

这是必要的。使用的“技巧”之一是 GCC 的 statement expressions需要这种“奇怪的”({ code }) 语法。

在大多数情况下,如果没有这个宏,使用这个宏的代码将无法编译(而且它不是有效的 C)。

另见: Rationale behind the container_of macro in linux/list.h

并且:container_of作者:Greg Kroah-Hartman。

关于c - 为什么我们需要在 block 宏周围加上括号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8142280/

相关文章:

c - 在 C 语言中编写结构体的规则是否因 Turbo C++ 编译器和 GCC 的不同而不同?

android - 如何直接发送触摸事件到/dev/input/event?

linux - 只从 backports 编译一个特定的驱动程序?

C、对结构队列进行排序

c++ - Windows 中的启动画面

c - 为什么我得到 "Segmentation Fault"?

c++ - 通过阅读 gcc 输出来学习汇编

c - 打印多个字符,格式为整数

c - linux kernel convert char * to uint8_t[6] (读字符串到mac)

c - 将指针移动 1 个结构 block