Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: do {...} while(0)? [duplicate]

Tags:

c

macros

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?

like image 475
igul222 Avatar asked Apr 22 '10 00:04

igul222


People also ask

What does while 0 do in C?

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.

Why do while 0 is used?

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.

What does while 1 mean in C?

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 loops in C?

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.


1 Answers

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; } 
like image 65
hamishmcn Avatar answered Oct 13 '22 21:10

hamishmcn