In Objective-C, when do you recommend using function-like macros over class or instance methods?
This shows that the macros are preprocessed while functions are not. In macros, no type checking(incompatible operand, etc.) is done and thus use of macros can lead to errors/side-effects in some cases. However, this is not the case with functions. Also, macros do not check for compilation error (if any).
Object-like Macros: An object-like macro is a simple identifier that will be replaced by a code fragment. It is called object-like because it looks like an object in code that uses it.
Speed versus size The main benefit of using macros is faster execution time. During preprocessing, a macro is expanded (replaced by its definition) inline each time it's used. A function definition occurs only once regardless of how many times it's called.
and as part of C++0x. Function-like macro definition: An identifier followed by a parameter list in parentheses and the replacement tokens. The parameters are imbedded in the replacement code. White space cannot separate the identifier (which is the name of the macro) and the left parenthesis of the parameter list.
They're very different things. A function or method exists exactly once in your code; a macro inserts its entire definition into your code every time you use it.
Some people take advantage of the fact that a short macro can expand into a chunk of code, rather like a cheap substitute for C++ style templates. Matt Gallagher's singleton macro is one example. And like templates, overuse of large macros can lead to surprisingly large code and big debugging headaches.
Aside from constants and tiny expressions, if you can use a function or method in place of a macro, you probably should.
It's hard to understand what you're actually asking, but I'd recommend functions over macros as a general rule since they perform type-checking, show clearer intent and will make debugging easier.
In my opinion, never. Macros are effectively text substitution tools that work at the compiler level, not while executing your code. This is useful for defining constants and such, but not good for more complex things.
Function-like macros seem to be used when there is a lot of repetition in the code, so you don't have to maintain the same routine in thirteen different places. However, if you can successfully use a macro in such a way, your code is poorly organized - you'd likely be better off refactoring it, and creating a single method to implement it.
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