Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad practice to have a macro definition return a value for a function?

Tags:

c++

c

macros

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)?

like image 259
Michael Chinen Avatar asked Aug 09 '11 23:08

Michael Chinen


People also ask

Can a macro return a value?

Macros just perform textual substitution. They can't return anything - they are not functions.

Can macros be defined inside a function?

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.

Can I use #define inside a function?

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.

Are C macros bad practice?

"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.


1 Answers

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.

like image 90
Oliver Charlesworth Avatar answered Nov 15 '22 07:11

Oliver Charlesworth