How do I resolve compiler error with my multi-lined macro in C
Let us look at the following plain multi-lined and multi-statement macro.
#define SAY_HELLO() \
printf("Hi, There!\n"); \
printf("Nice to meet you\n");
If you use the above macro as shown below, you will encounter compilation errors.
if(manager)
SAY_HELLO();
else
printf("You are not my manager..Why should I care?\n");
The above code expands to the following and results in compilation error as “else” part of the code is detached from the actual “if” condition.
if(manager)
printf("Hi, There!\n");
printf("Nice to meet you\n");
else
printf("You are not my manager..Why should I care?\n");
If you attempt to wrap all the statements of macro in {…}, general usage of the macro will throw an error.
#define SAY_HELLO() \
{ printf("Hi, There!\n"); \
printf("Nice to meet you\n"); }
General usage of the macro as shown below
SAY_HELLO();
will expand to
{ printf("Hi, There!\n");
printf("Nice to meet you\n"); };
and results in compilation error again.
To resolve this problem, it is advised to use a dummy loop “do {…} while(0)” around all the statements as shown below.
#define SAY_HELLO() \
do { \
printf("Hi, There!\n"); \
printf("Nice to meet you\n"); \
} while(0)
This will ensure that no compilation error occurs with any type of usage of the macro.

