C代码中在Linux中使用花括号的目的(包括 / linux / list.h)是什么?

4

我在Linux (include/linux/list.h)中发现了以下代码。我对第713行感到困惑。特别是,我不理解 ({ n = pos->member.next; 1; }) 这句话的含义。

这个花括号是做什么的?为什么这个语句中有一个'1'?

如果有人能解释这一行代码,那将不胜感激。请注意,我不需要关于链接列表和#定义工作原理等方面的解释。

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 

3
({ /* code */ }) 是 GNU 扩展语法,即一个声明-表达式。花括号内的代码将被执行,整个表达式的值为其中最后一个表达式的值。 - Daniel Fischer
2个回答

6
这是一个“语句表达式”。它是gcc扩展,根据6.1 Statements and Declarations in Expressions的文档:
“复合语句中的最后一件事应该是跟着分号的表达式;这个子表达式的值作为整个结构的值。”
在此情况下,对于以下代码:
({ n = pos->member.next; 1; })

这个值将会是1。根据文档:

这个功能在定义宏时非常有用(以便它们每个操作数只计算一次),使其变得“安全”。

下面是一个不使用语句表达式的示例:

#define max(a,b) ((a) > (b) ? (a) : (b))

与这个“安全”的版本相比,需要注意的是您要知道操作数的类型:
#define maxint(a,b) \
   ({int _a = (a), _b = (b); _a > _b ? _a : _b; })

这是Linux内核中使用的许多gcc扩展之一

3
任何有副作用的东西都有可能被应用两次。例如:max(a++, b) 会扩展成两个 a++,而不是像普通函数一样调用。 - Trillian

1
这是一种GNU语言扩展,称为语句表达式;它不是标准的C语言。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接