Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Purpose of Curly Brace Usage of C Code found in Linux (include/linux/list.h)?

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; }).

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

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 
like image 955
Akyidrian Avatar asked Mar 24 '23 15:03

Akyidrian


2 Answers

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; })

the value would be 1. According to the documentation:

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; })

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

like image 79
Shafik Yaghmour Avatar answered Apr 06 '23 09:04

Shafik Yaghmour


This is a GNU language extension known as a statement expression; it's not standard C.

like image 39
Oliver Charlesworth Avatar answered Apr 06 '23 09:04

Oliver Charlesworth