加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

在Linux中使用C代码的Curly Brace用途(include / linux / list.h

发布时间:2020-12-14 00:29:30 所属栏目:Linux 来源:网络整理
导读:我在 Linux中遇到了以下代码(include / linux / list.h).我对第713行感到困惑.特别是,我不明白({n = pos- member.next; 1;}). 花括号做什么?为什么这个陈述中有’1’? 如果有人能解释这一特定的行,我将不胜感激.注意,我不需要解释链接列表和#defines如何工
我在 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,member))
715

解决方法

这是一个声明表达式.它是 gcc extension并且根据文档 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.

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

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

值为1.根据文档:

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

它给出了这个例子而不使用语句表达式:

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

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

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

这是众多gcc extensions used in the Linux kernel中的一个.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读