6

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?

undur_gongor
  • 15,657
  • 5
  • 63
  • 75
SHH
  • 3,226
  • 1
  • 28
  • 41

2 Answers2

11

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.

Community
  • 1
  • 1
Mat
  • 202,337
  • 40
  • 393
  • 406
9

({...}) is a braced group, a code block that can be used inside an expression. The last statement determines its value.

Inside macros you use it to let macros behave the same way as functions. Mostly a static inline function would be preferable.

Related questions:

Community
  • 1
  • 1
Kijewski
  • 25,517
  • 12
  • 101
  • 143