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 #define
d 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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With