Linux (include/linux/list.h) 中 C 代码的花括号用法的目的? [英] Purpose of Curly Brace Usage of C Code found in Linux (include/linux/list.h)?

查看:28
本文介绍了Linux (include/linux/list.h) 中 C 代码的花括号用法的目的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Linux (include/linux/list.h) 中遇到了以下代码.我对第 713 行感到困惑.特别是,我不明白 ({ n = pos->member.next; 1; }).

I came across the following code within Linux (include/linux/list.h). I'm confused about line 713. In particular, I don't understand ({ n = pos->member.next; 1; }).

花括号在做什么?为什么这个语句中有一个1"?

What is the curly braces doing? Why is there a '1' in this statement?

如果有人能解释这一行,我们将不胜感激.注意,我不需要解释链接列表和#defines 是如何工作的,等等.

If someone could explain this particular line it would be much appreciated. Note, I don't need an explanation of how link lists and #defines work, etc.

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 

推荐答案

这是一个语句表达.这是一个 gcc 扩展,并且根据文档6.1 表达式中的语句和声明:

This is a statement expression. It is a gcc extension and according to the documentation 6.1 Statements and Declarations in Expressions:

复合语句的最后一件事应该是一个表达式后跟一个分号;这个子表达式的值作为整个结构的值.

The last thing in the compound statement should be an expression followed by a semicolon; the value of this subexpression serves as the value of the entire construct.

在这种情况下,对于代码:

Which in the case, for the code:

({ n = pos->member.next; 1; })

值为 1.根据文档:

此功能在使宏定义安全"(以便它们对每个操作数只计算一次)方面特别有用.

This feature is especially useful in making macro definitions "safe" (so that they evaluate each operand exactly once).

它给出了这个例子,没有使用语句表达式:

It gives this example without using statement expressions:

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

与这个安全版本相比,需要注意的是您知道操作数的类型:

versus this safe version, with the caveat that you know the type of the operands:

#define maxint(a,b) 
   ({int _a = (a), _b = (b); _a > _b ? _a : _b; })

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

This is one of the many gcc extensions used in the Linux kernel.

这篇关于Linux (include/linux/list.h) 中 C 代码的花括号用法的目的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆