在 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/