我在 Linux 中遇到了以下代码(include/linux/list.h)。我对第 713 行感到困惑。特别是,我不明白 ({ n = pos->member.next; 1; })。
大括号是做什么的?为什么这个语句中有一个“1”?
如果有人能解释这条特定的线路,我们将不胜感激。请注意,我不需要解释链接列表和#defines 如何工作等。
704 /**
705 * hlist_for_each_entry_safe - iterate over list of given type safe against removal of list entry
706 * @pos: the type * to use as a loop cursor.
707 * @n: another &struct hlist_node to use as temporary storage
708 * @head: the head for your list.
709 * @member: the name of the hlist_node within the struct.
710 */
711 #define hlist_for_each_entry_safe(pos, n, head, member) \
712 for (pos = hlist_entry_safe((head)->first, typeof(*pos), member);\
713 pos && ({ n = pos->member.next; 1; }); \
714 pos = hlist_entry_safe(n, typeof(*pos), member))
715
这是一个陈述表达式。它是一个海湾合作委员会扩展 https://stackoverflow.com/questions/3079721/are-statement-and-declarations-in-expressions-specific-to-gnu-c并根据文档6.1 表达式中的语句和声明 http://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html:
复合语句中的最后一项应该是一个表达式,后跟一个分号;该子表达式的值用作整个构造的值。
在这种情况下,对于代码:
({ n = pos->member.next; 1; })
该值将是1
。根据文档:
此功能对于使宏定义“安全”特别有用(以便它们对每个操作数执行一次)。
它给出了这个例子,但没有使用语句表达式:
#define max(a,b) ((a) > (b) ? (a) : (b))
与此相对safe版本,但需要注意的是您知道操作数的类型:
#define maxint(a,b) \
({int _a = (a), _b = (b); _a > _b ? _a : _b; })
这是众多之一Linux 内核中使用的 gcc 扩展 http://www.ibm.com/developerworks/library/l-gcc-hacks/.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)