Pergunta

i have one question and please help me.i have read on web page somthing about do while statement,different is that ,in while there is written 0,not boolean condition

do{
   // do some instruction
}while(condition );

is clearly understandable,but this one

 do
  {
    //again some instruction
  }while(0);

i can't guess what does it do?is it equivalence it to this: do something while(false)?or maybe is it infinity loop?please help me

Foi útil?

Solução

It does something only once. It is widely used in macros to group statements and make the usage more natural (i.e. require ending semicolon).

Any compiler worth its salt should ignore the do .. while altogether and just run the enclosed statements.

Outras dicas

Though this "loop" is executed just once, one may use it this way:

do
{
  // declare some local variables only visible here
  // do something

  if(TestSomeConditions())
      break;

  // do something more
  // destructors of local variables run here automatically
}while(0);

IMHO, in most cases it is better to rewrite this in a more structured manner, either this way

  // do something
  if(!TestSomeConditions())
  {
      // do something more
  }

or by introducing a separate function, reflecting the original scope:

  void MyFunction()
  {
      // declare some local variables only visible here
      // do something

      if(TestSomeConditions())
          return;

      // do something more
  }

It will treat 0 as false and one time loop will execute and break as soon as reached to while (g++ compiler tested).

The do while loop executes all the instructions in the body of the loop first and then checks for the condition. Hence, this loop just executes the instructions of the body of the loop once.

do
{
    //my instructions
}while(0)

is equivalent to writing

{
    //my instructions
}

The modern compilers are smart enough to optimize these things out!

Technically speaking, it makes it run once, as it checks (and fails the check) after it runs once.

Other than that, it's used in macros. For example:

#define blah(a) \
        something(1); \
        something(2)

if(a)
    blah(4);
else
    blah(19);

would lead to this:

...
if(a)
    something(1); something(2);
else
    something(1); something(2);

which is not valid syntax, as the else is not part of the if statement anymore. What you can do is:

 define blah(a) \
    do {
       something(1); something(2);
    } while(0)

    ...

which would translate into a single statement in the if block:

if(a)
    do { something(1); something(2); } while(0);
else
    ...
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top