3

Possible Duplicate:
Why are there sometimes meaningless do/while and if/else statements in C/C++ macros?
What's the use of do while(0) when we define a macro?
how does do{} while(0) work in macro?

I wonder what the use do{ ... } while(0) (... as a place-holder for other code) is, as it would, as far as I know, be exactly the same as just using ....

You can find code like this in the official CPython source. As an example, the Py_DECREF macro:

#define Py_DECREF(op)                                   \
    do {                                                \
        if (_Py_DEC_REFTOTAL  _Py_REF_DEBUG_COMMA       \
        --((PyObject*)(op))->ob_refcnt != 0)            \
            _Py_CHECK_REFCNT(op)                        \
        else                                            \
        _Py_Dealloc((PyObject *)(op));                  \
    } while (0)
Community
  • 1
  • 1
Niklas R
  • 16,299
  • 28
  • 108
  • 203
  • 2
    In general it lets you use `break` or `continue` to skip the remaining code without using `goto` or `return` (returning from the function completely). In your example the purpose is very different -- it forces the user to follow uses of the macro with a `;` without causing any compiler warnings. – ildjarn Feb 16 '12 at 18:35

1 Answers1

5

It makes compiler require ; so the macro looks like a function call:

Py_DECREF(x); // ok
Py_DECREF(x) // error
hamstergene
  • 24,039
  • 5
  • 57
  • 72