More C++ Idioms/Multi-statement Macro

= Multi-statement Macro =

Intent
To write a multi-statement (multi-line) macro.

Motivation
Sometimes it is useful to group two or more statements into a macro and call them like a function call. Usually, an inline function should be the first preference but things such as debug macros are almost invariably macros rather than function calls. Grouping multiple statements into one macro in a naive way could lead to compilation errors, which are not obvious at first look. For example,

would fail in an if statement if a semi-colon is appended at the end.

The above statement expands to

giving a compiler error. Therefore, people came up with a widely used idiom for multi-statement macros, which is based on a do-while loop.

Solution and Sample Code
Here is an example of the multi-statement macro idiom.

When the caller appends a semicolon, this expansion becomes a single statement regardless of the context. Optimizing compilers usually remove any dead tests, such as while(0). This idiom is not useful when macro is used as a parameter to a function call. Moreover, this idiom allows return statement.

Known Uses
ACE_NEW_RETURN, ACE_NEW_NORETURN macros in Adaptive Communication Environment (ACE).