为什么我们需要围绕块宏的括号?
在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的语句表达式 ,需要这种“奇怪的” ({ code })
语法。
在大多数用例中,使用此宏的代码不会编译(并且它不是有效的C)。
另请参见: linux / list.h中container_of宏背后的基本原理
并且:Greg Kroah-Hartman的container_of 。
({...})
是一个支撑组,一个可以在表达式中使用的代码块。 最后一个语句决定了它的价值。
在内部宏中,您使用它来让宏的行为与函数相同。 大多数情况下, static inline
函数更可取。
相关问题:
- ANSI C中的parens表达式包含复合语句(块)吗?
- ISO C等同于表达式中的支撑组