Purpose of Curly Brace Using the C code found on Linux (include / linux / list.h)?

I came across the following code on Linux (include / linux / list.h). I got confused on line 713. In particular, I do not understand ({n = pos-> member.next; 1;}).

What are curly braces? Why is there a "1" in this statement?

If someone can explain this particular line, it will be very appreciated. Please note: I do not need to explain 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 
+4
source share
2 answers

This is an expression of expression. This is a gcc extension and according to the documentation 6.1. Expressions and declarations in expressions

The last in the compound expression must be an expression followed by a semicolon; the meaning of this subexpression serves as the meaning of the whole construct.

What is the case for the code:

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

the value will be 1 . According to the documentation:

This function is especially useful when creating macro definitions "safely" (so that they evaluate each operand exactly once).

He gives this example without using operator expressions:

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

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

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

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

+6
source

This is an extension of the GNU language, known as an expression; This is not standard C.

+1
source

Source: https://habr.com/ru/post/1485338/


All Articles