问题
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
回答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; })
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.
回答2:
This is a GNU language extension known as a statement expression; it's not standard C.
来源:https://stackoverflow.com/questions/17015375/purpose-of-curly-brace-usage-of-c-code-found-in-linux-include-linux-list-h