4.1. Inlining functions


Inlining

When a compiler inlines a function, it takes the function body and places it directly in the code for the calling function. This eliminates the overhead of a procedure call, which can be a big gain for tiny functions that are called frequently. It can also help with big functions that are called frequently, but only from one or two places in the code. For large functions that are called from many places, it is not such a good idea, as it tends to make the code much larger which can reduce the efficiency. It is also completely impossible with recursion functions.

Under GCC, one requests that a function be inlined by preceeding the function definition with the keyword inline. For example:

inline int min(int x, int y)
{
    return (x < y) ? x : y;
}

GCC does not actually perform inlining unless you are doing an optimising compile e.g. with -O2.


Macros

You may have noticed that inlined functions are doing a very similar job to macros. So what are the differences? Here are a few:

  1. Macros evaluate their arguments every time they are referenced. Inline functions behave like normal functions and only evaluate their arguments once.
  2. Inline functions are generally easier to debug, since any errors in the function manifest themselves when the function is defined, not when it is used. One can also step into inlined functions in a debug build (without optimisation).
  3. Macros are not type-specific, but on the other hand provide no type safety.
  4. Macros are more flexible, since they work at the lexical level. They allow things like concatenating two arguments into a single token.

Generally it is better to use inline functions than macros where possible, largely due to the first point above.


[Prev] [Next] [Up]

Last updated Sun Nov 28 22:37:23.0000000000 2004. Copyright Bruce Merry (bmerry '@' gmail dot. com).