0

I found some strange syntax while reading linux source code. The container_of macro looks like

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

what confused me is the syntax like ({statement1; statement2;})

I tried some simple code like

int a = {1;2;};

I compiled it with gcc. After running, 'a' seemed to be 2. But it couldn't be compiled with Microsoft VC++. Is this syntax an expanded feature of gcc? If so, how can I get the same effect without gcc expansion, like define multiple statements and return a value by using macro?

Arthur
  • 13
  • 3
  • **Why do you ask?** The Linux kernel needs `gcc` (or a very compatible compiler, like recent versions of *TinyCC* or of *LLVM/Clang*) to be compiled. – Basile Starynkevitch Jul 17 '13 at 14:04

1 Answers1

2

The ({...}) syntax is a GCC extension, called statement expressions.

The typeof is another GCC extension.

Both extensions are available in some other compilers, like LLVM/Clang (or TinyCC).

The Linux kernel uses them quite often.

It would be quite difficult to avoid them. If you really wanted to, you might consider (and this is a non trivial task), some conversion from GIMPLE back to low-level, non-portable and unreadable C. You might use MELT for that (part of the job is done in its file melt/xtramelt-c-generator.melt by J.Salvucci).

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
  • Thank you. There are many masterly codes in Linux kernel that are valuable references for me. But sometimes I'm not allowed to use gcc, so I think I should try some other methods to get the similar effect in other compilers. – Arthur Jul 17 '13 at 16:00
  • I have no idea who forbids you (and why) using `gcc` but you could then use `clang` which accepts same language extension. – Basile Starynkevitch Jul 17 '13 at 16:13