Possible Duplicates:
Why are there sometimes meaningless do/while and if/else statements in C/C++ macros?
do { … } while (0) what is it good for?
I'm working on some C code filled with macros like this:
#define SAFE_FREE(x) do { if ((x) != NULL) {free(x); x=NULL;} } while(0)
Can anyone explain what this macro does, and why do {} while(0)
is needed? Wouldn't that just execute the code once?
The while(0) loop means that the condition available to us will always be false. The execution of the code will, thus, never really occur.
You may see a do loop with the conditional expression set to a constant value of zero (0). This creates a loop that will execute exactly one time. This is a coding idiom that allows a multi-line macro to be used anywhere that a single statement can be used.
The while(1) or while(any non-zero value) is used for infinite loop. There is no condition for while. As 1 or any non-zero value is present, then the condition is always true. So what are present inside the loop that will be executed forever.
do { statement(s); } while( condition ); Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop executes once before the condition is tested. If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop executes again.
BTW On the C++ Style and Technique FAQ Bjarne Stroustrup suggests using an inline (template) function to do a "delete and null"
template<class T> inline void destroy(T*& p) { delete p; p = 0; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With