Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we need parentheses around block macro?

In linux, container_of macro is enclosed in seemingly "extra" parentheses:

 #define container_of(ptr, type, member) ({ \
                const typeof( ((type *)0)->member ) *__mptr = (ptr); 
                (type *)( (char *)__mptr - offsetof(type,member) );})

Instead of it, can we just use

 #define container_of(ptr, type, member) { \
                const typeof( ((type *)0)->member ) *__mptr = (ptr); 
                (type *)( (char *)__mptr - offsetof(type,member) );}

?

Are the parentheses mandatory or are they just for precaution?

like image 590
SHH Avatar asked Nov 15 '11 19:11

SHH


1 Answers

It's necessary. One of the "tricks" used is GCC's statement expressions that require this 'strange' ({ code }) syntax.

Code that uses this macro wouldn't compile without that in most use cases (and it's not valid C).

See also: Rationale behind the container_of macro in linux/list.h

And: container_of by Greg Kroah-Hartman.

like image 105
Mat Avatar answered Oct 11 '22 09:10

Mat