6

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
l0b0
  • 55,365
  • 30
  • 138
  • 223

3 Answers3

9

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.

Benoit
  • 76,634
  • 23
  • 210
  • 236
2

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.

Praetorian
  • 106,671
  • 19
  • 240
  • 328
1

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.

Kevin
  • 53,822
  • 15
  • 101
  • 132