Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why `do { ...; exit(...); } while (0)` in C? [duplicate]

As a C newbie I'm having trouble understanding the following code:

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

I gathered that the reason this function is #defined is to override an existing function, but what is the point of a do ... while(0) loop with an unconditional exit() statement? Is it not possible to write this without the loop construct?

like image 667
l0b0 Avatar asked Mar 21 '13 14:03

l0b0


3 Answers

Many duplicates here I think.

The do...while(0) trick enables you to use errExit in various contexts without breaking anything:

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

is translated to:

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

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

like image 71
Benoit Avatar answered Nov 17 '22 06:11

Benoit


Assume the macro didn't have the do { ... } while(0) loop, just the 2 statements inside. Now, what if I were to write

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

My conditional exit has become a non-conditional exit.

like image 37
Praetorian Avatar answered Nov 17 '22 07:11

Praetorian


The do { ... } while(0) construct is common, and usually considered best practice, for macro functions of multiple statements, such as this. It allows use as a single statement, so there are no surprises.

like image 44
Kevin Avatar answered Nov 17 '22 08:11

Kevin