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?
-
Nice question, I've wondered the same! +1Kiril Kirov– Kiril Kirov2013年03月21日 14:37:16 +00:00Commented Mar 21, 2013 at 14:37
-
Too bad the title duplicate detector didn't pick up this...l0b0– l0b02013年03月21日 14:42:10 +00:00Commented Mar 21, 2013 at 14:42
3 Answers 3
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.
5 Comments
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.
Comments
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.
Comments
Explore related questions
See similar questions with these tags.