Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of ({ ... }) brackets in macros to swallow the semicolon

Tags:

c

macros

Often, in macros, you will see people use a do { ... } while(0) to swallow the semicolon. I just came across an example where they use ({ ... }) instead, and it seems to not only swallow the semicolon, but seems to allow you to return a value as well:

#define NEW_MACRO()  ({ int x = 1; int y = 2; x+y; })

 if(1) 
   val = NEW_MACRO(); 
 else 
   printf("this never prints");`

val would come out being 3. I can't find any documentation on it, so I'm a bit wary of it. Are there any gotcha's with this method?

like image 822
John Ulvr Avatar asked Mar 23 '11 18:03

John Ulvr


2 Answers

This is not valid in standard C.

Some compilers may have extensions (e.g. GCC's statement expressions) that allow this sort of thing.

like image 94
Oliver Charlesworth Avatar answered Nov 15 '22 05:11

Oliver Charlesworth


As Oli said correctly this was invented by gcc. The goal is (often with their typeof extension) to be able to evaluated macro elements only once and use this computed value later on by using a name.

Many times such a use can be completely avoided by using inline functions. These also have the (dis)advantage of being more strict on types.

In some other cases where you just need a temporary variable whose address you pass to a function, C99 also has compound literals that can be used for this.

like image 26
Jens Gustedt Avatar answered Nov 15 '22 07:11

Jens Gustedt