What is the use of do{}while(0)? [duplicate]
Pergunta
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)
Solução
It makes compiler require ;
so the macro looks like a function call:
Py_DECREF(x); // ok
Py_DECREF(x) // error
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow