A trivial do/while loop is an useful technique in C programming to make a multi-statement macro. Consider the following multi-statement C preprocessor macro and if-statement with two branches:

#define aemb(x) { do_this(x); do_that(); }

if (x > y)
aemb(x); // Branch 1
else
aemb(y); // Branch 2

Compiling these codes would give a parse error, because the first semicolon after do_this(x) terminates the if-statement, and causing ‘else’ unexpected. To make matter worse, the solution of sandwiching the multi-statement in curly braces would not work, because the trailing semicolon will cause havoc with if/else.

The workaround for this is to sandwich the multi-statement block with do and while (0). The multi-statement now becomes:

#define aemb(x)   do   {  do_this(x); do_that();  }   while (0)

and finally the compiler is happy.


0 Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.