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)?
Macros just perform textual substitution. They can't return anything - they are not functions.
You cannot define a macro within a function and then use it within the same function. That's just not how the language works. Macros are expanded before the function is run. If the macro is defined inside the function, then by definition it cannot exist before the function is run.
You can use it inside a function, but it is not scoped to the function. So, in your example, the second definitions of a macro will be a redefinition and generate an error. You need to use #undef to clear them first.
"Macros are unsafe, have no type checking and should be avoided whenever possible. An alternative to macro is inline function for some use cases." He is right that a macro doesn't respect a namespace. That's just a caveat of using one.
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.
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