Saturday, June 18, 2011

C++ note: commas and brackets in a macro

Sometimes it's handy to use a macro to avoid repeated writing of similar code, especially when there is no direct way to modularize some apparently similar but essentially very different functions. In such uses of macros it often occurs that commas and brackets need to be included in the macro. Direct inclusion of commas and brackets may confuse the compiler.

#define example_macros(left_code, right_code)\
left_code a right_code\
left_code b right_code\
left_code c right_code\
left_code z right_code

void func_1() {
example_macros( , ); );

void func_2() {
example_macros( cout<< , <<(endl); );

When the usage become more complex, particularly when there are more arguments to macro, commas and brackets may confuse the macro. The bets solution I have found is using extra macros.

#define id_comma ,
#define id_left_bracket (
#define id_right_bracket )

and then replace the usage of commas and brackets in macros

void func_1() {
example_macros( id_left_bracket , id_right_brackt ; );

This will avoid any confusion.