Yes this is bad. Use goto .
#define fail_unless(x) do {if(!(x)) goto fail;} while (0) int foo() { fail_unless( my_write(...) ); fail_unless( bar() ); return 0; fail: cleanup(); return -1; }
Edit : if you are understated because you donโt understand what the while loop is doing there, you should just ask. This is the standard method for ensuring that the C macro acts as a single statement in any context. If your macro expands to an if statement (for example, macros in another, pending answers), you get unexpected side effects, for example:
#define DONT_DO_THIS(x) if (!x) { foo; } if (a) DONT_DO_THIS(x) else something_else();
It was expected that something_else would execute when !a , but what the macro actually expands is:
if (a) if (!x) { foo;} else something_else();
And something_else is executed when a && x , and not when !a , as the programmer planned.
source share