Use of ({ ... }) brackets in macros to swallow the semicolon
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; })
开发者_JAVA技巧
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?
This is not valid in standard C.
Some compilers may have extensions (e.g. GCC's statement expressions) that allow this sort of thing.
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.
do { ... } while(0)
is not for the "swallowing the semicolon". It is for turning the C expression to the C statement.
精彩评论