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,92772 gold badges63 silver badges135 bronze badges
asked Mar 21, 2013 at 14:33
2
  • Nice question, I've wondered the same! +1 Commented Mar 21, 2013 at 14:37
  • Too bad the title duplicate detector didn't pick up this... Commented Mar 21, 2013 at 14:42

3 Answers 3

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.

answered Mar 21, 2013 at 14:35
Sign up to request clarification or add additional context in comments.

5 Comments

Why would plain old braces not do the job?
Nice! +1. That's really clever and tricky.
Ah, so the whole idea is to keep the resulting code to a single statement as seen from the surrounding code? Neat!
@Joe Read the complete answer here stackoverflow.com/a/154138/1488917
@Joe: No. Because of semicolon. As said by AshRj the answer provided elsewhere is thorough.
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.

answered Mar 21, 2013 at 14:35

Comments

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.

answered Mar 21, 2013 at 14:36

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.