Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 322
  • Last Modified:

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
0
arut
Asked:
arut
  • 3
1 Solution
 
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:
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
 
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

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now