Using a macro defined to conditionally return a value has a disadvantage where it is not apparent from only looking at the client code might exit at the point of the macro.
The use case I am considering is writing a value and error checking, like so:
#define WRITE_CHK(file, param)\
if (!write_that_returns_zero_on_fail(file, param)) {\
handle_error();\
return false;\
}
client code:
bool myfunc()
{
...
WRITE_CHK(file, param) // function might return here
...
return true;
}
I am curious if the benefits of the macro (which would be used in many places in my code) would outweigh the disadvantage mentioned above.
Are there preferred alternatives besides simply expanding (not using the macro)?
The standard answer is “don’t use macros”; but that’s often slightly simplistic. There are sometimes cases where they can greatly cut down on the boilerplate verbosity that you’d otherwise have.
So, why not encode the fact into the macro name? e.g.
WRITE_OR_RETURN_ON_FAILURE. It may be slightly verbose, but it’s much less likely to trip up readers of your code.