Why use while (0)?

37

In the Linux code I saw some macros with:

do
{

}while(0) 

Is there a reason? Because apparently there is no logic to a loop of repetition where the code repeats only once.

    
asked by DaviAragao 13.08.2015 в 21:13
source

2 answers

46

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

It serves to group multiple commands without causing errors when the preprocessor expands the 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 the same usage error:

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

Why would it be expanded to:

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

It would work if you had not used the semicolon in the macro line, but no one else does this. And it would be a mistake to force the programmer to 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++;

Obviously it would destroy the use of if as you imagined and else would be loose, generating a syntax error.

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

    
answered by 13.08.2015 / 21:27
source
6

It's also a way to avoid if it's extremely clustered and simplify error checking:

do {
  // faça algo
  if (error) {
    break;
  }
  // faça alguma outra coisa
  if (error) {
    break;
  }
  // etc..
} while (0);
    
answered by 24.08.2015 в 22:58