Saturday, July 23, 2011

Inline Functions in C


An inline function is one for which the compiler copies the code from the function definition directly into the code of the calling function rather than creating a separate set of instructions in memory. Instead of transferring control to and from the function code segment, a modified copy of the function body may be substituted directly for the function call. In this way, the performance overhead of a function call is avoided.
A function is declared inline by using the inline function specifier or by defining a member function within a class or structure definition. The inline specifier is only a suggestion to the compiler that an inline expansion can be performed; the compiler is free to ignore the suggestion.
  • In this example all the declarations and definitions use inline but one adds extern:
    // a declaration mentioning extern and inline
    extern inline int max(int a, int b);
    // a definition mentioning inline
    inline int max(int a, int b) {
    return a > b ? a : b;
    }
    In this example, one of the declarations does not mention inline:
    // a declaration not mentioning inline
    int max(int a, int b);
    // a definition mentioning inline
    inline int max(int a, int b) {
    return a > b ? a : b;
    }
    In either example, the function will be callable from other files.
    
    
  • A function defined static inline. A local definition may be emitted if required. You can have multiple definitions in your program, in different translation units, and it will still work. Just dropping the inline reduces the program to a portable one (again, all other things being equal).
    This is probably useful primarily for small functions that you might otherwise use macros for. If the function isn't always inlined then you get duplicate copies of the object code, with the problems described above.
    A sensible approach would be to put the static inline functions in either a header file if they are to be widely used or just in the source files that use them if they are only ever used from one file.

    In this example the function is defined static inline:
    // a definition using static inline
    static int max(int a, int b) {
    return a > b ? a : b;
    }
The first two possibilities go together naturally. You either write inline everywhere and extern in one place to request a stand-alone definition, or write inline almost everywhere but omit it exactly once to get the stand-alone definition.
main is not allowed to be an inline function.

No comments:

Post a Comment