2

Possible Duplicate:
Why are there sometimes meaningless do/while and if/else statements in C/C++ macros?

Why is C source code I run across sometimes wrapped with a do...while(0) loop?

do {
  parser->http_errno = e;                         
  parser->error_lineno = __LINE__;    
} while (0) 

Why use that, versus this:

parser->http_errno = e;                         
parser->error_lineno = __LINE__;    

I suspect this has something to do with thread safety, but I'm not sure.

Community
  • 1
  • 1
kiennt
  • 1,514
  • 2
  • 14
  • 13

2 Answers2

2

It's done so that you can use it inside a macro, while requiring the macro user to use a semicolon at the end, just like a regular statement.

In other words, whenever you want multiple statements inside a function-like macro FOO(...), you wrap it with do { ... } while (0) so that the user of the macro can (and, in fact, must) call it as FOO(x);, instead of simply FOO(x) (whose lack of semicolon can be weird for both humans and computers).

user541686
  • 205,094
  • 128
  • 528
  • 886
  • 1
    It's not just to disallow `FOO(x)`, but to prevent `if (foo) FOO(x); else BAR(x);` from breaking. The `{}` block would be the body of the `if`, and the `;` would be an extra empty statement separating the `if` from the `else`, making the `else` invalid. – R.. GitHub STOP HELPING ICE Apr 12 '12 at 04:57
0

You see such code mostly in Macros and they behave as if they were function #define Whatever do ..... while(0)

and you use it like Whatever();

Ups I see this question was answered here before do { ... } while (0) — what is it good for?

Corrected the link, thanks Rune.

Community
  • 1
  • 1
Friedrich
  • 5,916
  • 25
  • 45