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,304
  • 4
  • 59
  • 73
SHH
  • 2,916
  • 1
  • 23
  • 40

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
  • 195,986
  • 40
  • 382
  • 396
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
kay
  • 24,516
  • 10
  • 94
  • 138