Why use "while(0)"?

Asked

Viewed 1,031 times

38

In Linux code I saw some macros with:

do
{

}while(0) 

Is there a reason? Because there seems to be no logic in a repeat loop where the code repeats only once.

  • 1

    This question in Soen is identical:Why while(0)

  • 1

    Related: http://answall.com/questions/78493/qual-%C3%A9-a-utility-e-import%C3%A2ncia-de-do-while

  • 1

    This is not the while infinity. The test will always be false. So it is a do. while, if it were not, nor would it enter. For infinity it should be while(1).

  • Normally the ; at the end of the macro; that ; comes from the code itself.

  • 3

    Man, I see everybody questioning this! What does it have to do with being on the Soen? Not everyone can read English :)

  • It is for the purpose of macro declaration.

Show 1 more comment

2 answers

48


It probably does not exist because it is little needed and it can be solved in this way. Anyway this construction is used essentially in macros (I think you already knew this by tags original of the question).

It serves to group multiple commands without causing errors when the preprocessor expands code.

Example:

#define MACRO(x) do { funcao(x); x++; } while (0)

Can be used in:

if (a > 0)
    MACRO(a);
else
    a++;

This would cause error in the same use:

#define MACRO(x) { funcao(x); x++; }

Because it would be expanded to:

if (a > 0)
    { funcao(x); x++; };
else
    a++;

It would work if you hadn’t used the semicolon in the macro line, but nobody does it. And it would be a mistake to make the programmer know that this macro should be used like this.

This is even worse:

#define MACRO(x) funcao(x); x++

Expand to:

if (a > 0)
    funcao(x); x++;
else
    a++;

I put in the Github for future reference.

It would obviously destroy the use of if as imagined and the else would be loose, generating a syntax error.

In some cases it is possible to use this in normal code, but it is rare to be useful and readable.

  • In addition to what Manero said, there is also the issue of flow control with "continue" and "break" which requires scopes such as "do/while". I don’t know if these macros use it for that, but it serves to control more freely. You can, for example, set conditions where the loop is repeated and then "continue", as well as you can change the condition of the loop to 1 or true (C++) and set conditions where the loop ends using "break.

7

It is also a way to avoid if’s greatly grouped and simplify error checking:

do {
  // faça algo
  if (error) {
    break;
  }
  // faça alguma outra coisa
  if (error) {
    break;
  }
  // etc..
} while (0);
  • 3

    To summarize in a nutshell: if you break in this ... while(0) block, it is a disguised "drop".

  • 3

    @epx exactly, it is the construction of complicated structures just to say it did not use goto: http://answall.com/q/20660/101

Browser other questions tagged

You are not signed in. Login or sign up in order to post.