Inline functions in C++

(From http)
Inline functions
Inline functions are functions where the call is made to inline functions. The actual code then gets placed in the calling program.
Inline functions eliminate function-call overhead. The programmer uses the key word inline to advise the compiler to generate function code in line (when possible ) to minimize function calls. The compiler could choose to ignore the inline advice.
The inline qualifier should be sued only with small, frequently used functions.
Member functions defined in a class definition are automatically inlined. The compiler reserves the right not to inline any function.


Comparison to macros
Traditionally, in languages such as C, inline expansion was accomplished at the source level using parameterized macros. Use of true inline functions, as are available in C++, provides several benefits over this approach:
    * Macro invocations do not perform type checking, or even check that arguments are well-formed, whereas function calls usually do.
    * In C, a macro cannot use the return keyword with the same meaning as a function would do (it would make the function that asked the expansion terminate, rather than the macro). In other words, you cannot make the macro return something which is not the result of the last expression invoked inside it.
    * Since C macros use mere textual substitution, this may result in unintended side-effects and inefficiency due to re-evaluation of arguments and order of operations.
    * Compiler errors within macros are often difficult to understand, because they refer to the expanded code, rather than the code the programmer typed.
    * Many constructs are awkward or impossible to express using macros, or use a significantly different syntax. Inline functions use the same syntax as ordinary functions, and can be inlined and un-inlined at will with ease.
    * Debugging information for inlined code is usually more helpful than that of macro-expanded code.
Many compilers can also inline expand some recursive functions; recursive macros are typically illegal.
Bjarne Stroustrup, the designer of C++, likes to emphasize that macros should be avoided wherever possible, and advocates extensive use of inline functions.

No comments: