2

Possible Duplicate:
Do-While and if-else statements in C/C++ macros
What’s the use of do while(0) when we define a macro?

I often see a code like this:

#define foo() do { xxx; yyy; zzz; } while (0)

Why do-while wrapper is used here? Why not simply

#define foo() { xxx; yyy; zzz; }

?

EDIT : removed semicolon.

Community
  • 1
  • 1
  • 2
    I bet you rather see `#define foo() do { xxx; yyy; zzz; } while (0)` (without the trailing semi-colon - that's exactly why...) –  Dec 12 '12 at 18:41
  • 1
    search for `[c]while (0)` in the SO search bar, you'll get piles of answers to this. – Mike Dec 12 '12 at 18:42
  • He is asking why are they not simply writing `{}` rather than `do{}while(0)`. So this is _not_ a duplicate and the link doesn't answer the question! Voting to reopen. – Lundin Dec 12 '12 at 19:04
  • 5
    Link from other post does answer the question: http://gcc.gnu.org/onlinedocs/cpp/Swallowing-the-Semicolon.html – mlibby Dec 12 '12 at 19:18
  • 1
    @Lundin - See the answer (link) from user:raghava on that other post. – Mike Dec 12 '12 at 19:26
  • @mcl No, that doesn't answer why you can't simply type {}. – Lundin Dec 12 '12 at 19:40
  • @WilliamPursell No, we just had the question re-opened since that link does not answer why you can't simply type {} instead of do{}while(0). – Lundin Dec 12 '12 at 19:41
  • 1
    @Lundin The 4th code block of the accepted answer addresses that portion of the question. – William Pursell Dec 12 '12 at 19:53
  • The excellent comp.lang.c FAQ is [here](http://www.c-faq.com/). You've just asked question 10.4. – Keith Thompson Dec 12 '12 at 20:07
  • @WilliamPursell Ah right, there we have it then. – Lundin Dec 12 '12 at 20:15

1 Answers1

3

Here's the simple answer.

#define foo() do { xxx; yyy; zzz; } while (0)
#define foo() { xxx; yyy; zzz; }

if (condition)
    foo();
else
    x++;

When you use the do-while version, that will get correctly expanded to:

if (condition)
    do { xxx; yyy; zzz; } while (0);
else
    x++;

When you use the {} version, that will get expanded to this, which is a syntax error (no matching if for the else). Note the extra semicolon in the second line.

if (condition3)
    { xxx; yyy; zzz; };
else
    x++;
Bill Lynch
  • 80,138
  • 16
  • 128
  • 173