Linux内核container_of宏中复合语句的语义及赋值原理咨询
关于Linux内核中container_of宏的复合表达式语法疑问
我在浏览Linux内核代码时,看到container_of.h中的container_of宏定义如下:
#define container_of(ptr, type, member) ({ \ void *__mptr = (void *)(ptr); \ static_assert(__same_type(*(ptr), ((type *)0)->member) || \ __same_type(*(ptr), void), \ "pointer type mismatch in container_of()"); \ ((type *)(__mptr - offsetof(type, member))); })
我清楚这个宏的功能——之前用过侵入式链表,但我常用的是更简洁的单行版本:
#define container_of(__ptr__, __type__, __member__) ((__type__*)(__ptr__ - offsetof(__type__, __member__)))
我不理解的是这种多行语句在赋值操作中的语义。通常我们会这样使用这个宏:type* name = container_of(ptr, type, member)
展开后代码如下:
type* identifier = ({ void *__mptr = (void *)(ptr); static_assert(__same_type(*(ptr), ((type *)0)->member) || __same_type(*(ptr), void), "pointer type mismatch in container_of()"); ((type *)(__mptr - offsetof(type, member))); })
我自己写了个简单的验证示例:
#define POC(__x__) ({assert(__x__ == __x__); 2;}) int __x__ = POC(0); printf("__x__: {%d}", __x__); // 输出2
我有几个疑问:
- 这种写法为什么能编译通过?
- 在单次赋值中使用多条语句的语义是什么?
- 是否总是取最后一个表达式的值作为赋值结果?
- 我知道C语言里可以用大括号创建新作用域实现变量遮蔽,但从没见过把作用域直接嵌入赋值的用法,希望得到解释。
内容的提问来源于stack exchange,提问作者ca-hercor
相关产品推荐
相关产品推荐

