for a lot of quick tasks where one could employ a function f(x,y)
, in plain C, macros are used. I would like to ask specifically about these cases, that are solvable by a function call (i.e. macros used for inlining functions, not for code expansion of arbitrary code).
Typically C functions are not inlined since they might be linked to from other C files. However, static C functions are only visible from within the C file they are defined in. Therefore they can be inlined by compilers. I have heard that a lot of macros should be replaced by turning them into static functions, because this produces safer code.
Are there cases where this is a not good idea?
Again: Not asking about Code-Production macros with ## alike constructs that cannot at all be expressed as a function.
7
Macros that are solvable by a function call have a lot of pitfalls:
- They are hard to write, because you may have to handle properly arguments like
++i
. - They are hard to debug with a visual debugger since you cannot step through a macro
or put a breakpoint there. - They are hard to handle correctly when analysing compilations dependencies.
Macros that are solvable by a function call could have been useful to provide inlining in a primitive compiler. I am not aware of any compiler not handling inline functions and some can even inline across compilation units.
Typically C functions are not inlined since they might be linked to from other C files.
There is no reason why a compiler would not be able to provide two versions of a function, a traditional call
ed one and an inline
d one. You should look at the documentation of the compiler you are targetting. Also, you may want to look at generated assembly: even if you do not know assembly, you can quickly learn to tell if some function has been inlined or not. (Start with baby-examples to quickly learn this.)