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,438
  • 68
  • 55
  • 126
l0b0
  • 52,149
  • 24
  • 132
  • 195

3 Answers3

8

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
  • 73,313
  • 23
  • 201
  • 230
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
  • 103,386
  • 18
  • 232
  • 318
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
  • 51,293
  • 15
  • 96
  • 128