Why `do {...; Output(...); } while (0) `in C?

As a newbie to C, I had trouble understanding the following code :

#define errExit(msg) do { perror(msg); exit(EXIT_FAILURE); \ } while (0) 

I realized that the reason for this function is #define d to override the existing function, but what is the point of the do ... while(0) with the unconditional expression exit() ? Is it impossible to write this without a loop construct?

+4
source share
3 answers

A lot of duplicates here, I think.

The do...while(0) trick allows using errExit in various contexts without breaking anything:

 if(x) errExit(msg); else return 1; 

translates to:

 if(x) do { ...; ...; } while(0); else return 1; 

If you omit the do...while(0) , then you cannot reliably add a semicolon, for example.

+7
source

Suppose a macro does not have a do { ... } while(0) , but only 2 statements inside. Now what if i write

 if( foo() ) errExit("foo!" ); 

My conditional exit was not a conditional exit.

+2
source

The do { ... } while(0) construct is common and is generally considered best practice for macro functions of several operators such as this. This allows you to use as a single statement, so there are no surprises.

+1
source

All Articles