Home > Learning > C/C++ inline keyword

C/C++ inline keyword

It’s always been fuzzy in my mind what inline does. An ex-colleague who had discovered it said it was to make things faster, but I was certain it wasn’t just a magic word. Now it’s a bit clearer.

Suppose you have a very simple function:

int add(int a, int b)
{
    return a + b;
}

That’s not very processing intensive, right? But when this is compiled, what happens? Well, it’s a function, and a function has a place in memory. When the function is called in execution, the context is changed to reach that “add” function, execute it, and return the result (my simplification of the wording betrays my lack of knowledge of assembly, I know). So that’s basically three operations for a simple addition. One way to speed that up is to tell the compiler to make this function inline, that is to say, to not leave the context for when it is called. In other words, the function’s code replaces each call.

inline int add(int a, int b)
{
    return a + b;
}

It keeps the logic nice and tidy, but at the same time speeds up execution. There is a downside, however: the program will have a larger memory footprint. That means it could, in the end, slow down execution (if there are many inline functions).

One nice way to use this is for C++ accessors:

// myclass.h
class MyClass
{
private:
    int m_int;
public:
    int GetInt() const;
    void SetInt(int);
}

inline int MyClass::GetInt() const
{
    return m_int;
}
inline void MyClass::SetInt(int value)
{
    m_int = value;
}

Put the inline functions in your header file, and you’re all set.

Categories: Learning Tags: ,
  1. 2012-12-22 at 6:08 pm

    Writing function within class is better or not ? which is smart?

    • MPelletier
      2012-12-23 at 3:49 pm

      Can you give a specific example? I don’t understand your question.

  1. No trackbacks yet.

Leave a comment