• C

do{ }while (0) loop usage

Can somebody please explain the usage of do while(0) loop in C.An example would be useful.

Thanks,
arut
arutAsked:
Who is Participating?
 
djbusychildCommented:
Coming from a UNIX background and hacking around kernels you see do {} while(0) a lot.

These are usually used when you're defining MACROs. In order to ensure that people can use the MACRO within a control block without any worries. For example the Berkeley queue uses do {} while() for all their MACROs

look at the following example

#include <stdio.h>
#define MYMACRO { \
                  printf ("hello world"); \
                }

int main(int argc, char* argv[])
{
        if (1)
            MYMACRO ;
        return 0;
}

many people put ";" at the end of a macro call, and this will not work well. so you do the following


#include <stdio.h>
#define MYMACRO do { \
                  printf ("hello world"); \
                } while(0)

int main(int argc, char* argv[])
{
        if (1)
            MYMACRO ;
        return 0;
}

It's just an old trick. =)
0
 
newmangCommented:
Are you sure you don't mean do while(1)?

if you have a do while loop like the following

do
   statement
   statement
while(value)

The loop will execute while value is true (ie not=zero), when value hits zero the loop will end.

Consequently if you have the following as you ask

do
   statement
   statement
while(0)

Then the loop will execute only once, therefore you might as well not bother with the do or while() statements.

What is more common is to use a do..while(1) loop to form an endless loop as follows

do
   statement
   statement
while(1)

This will go on ad infinitum. It is often used for a server type daemon where it runs forever until a signal is caught and some other signal handler code kills the application.

You can also use a break command internally to break the loop as follows

do
    get character from keyboard
    process character
    if character = Q or q
        break
    do some more stuff
    and more stuff
while(1)
stuff that gets done when q has been entered

Cheers - Gavin
0
 
djbusychildCommented:
actually, I should have really put an "else" block there to show you exactly why, but you get the idea.
0
 
arutAuthor Commented:
Thanks for the simple example :)
0
 
djbusychildCommented:
yo, wassupt wit da 'B', man? --;
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.