C/C++ Do While Idiom

Recipe # | posted in Programming | Comments

1 – Problem Description

Safely create macros in C/C++

2 – Solution

1
2
3
4
5
6
#define FOO(s) { dummy(s); yummy(s); }

if (...)
  FOO(str); /* expands to => { dummy(str); yummy(str); }; */
else
  goo(str);

After macro substitution we have

1
2
3
4
if (...)
  { dummy(str); yummy(str); };
else
  goo(str);

Can you spot the problem? ….ahaaaaa ;) The first two lines are seen as a complete if statement by the compiler. Thus the remaining two,

1
2
else
    goo(str);

are seen as a separate else clause that doesn’t belong to any if! To avoid such kind of ugly errors, wrap the statement in a do loop whose condition is false

1
do { ... } while (0)

Since a do loop must always be followed by a ;, we are avoiding such kind of problems. Therefore for the above example we should write

1
2
3
4
5
#define FOO(s)            \
        do {              \
                dummy(s); \
                yummy(s); \
        } while (0)

So now when replaced, FOO(str), must followed by a ;

Comments