Thomas Sampson

C++ Inline keyword

Leave a comment

Today I came across the inline keyword in c++. The inline keyword can be placed before a function defenition and is usually placed before functions which contain only a few lines of code.

If you have written a function which is only 3 lines of code for example, and these 3 lines of code are fairly simple and non resource-expensive, some compilers will automatically inline your function. However, the inline keyword is a way of enforcing that this happens at compile time. So what is function inlining?

Function inlining allows the compiler to substitute any calls to your function with the actual function definition it’s self. Let’s say you have a call to a function go(). Without function inlining, at runtime all sorts will go off. Register values, any paramaters and the instruction pointer will be pushed onto the stack (time consuming), the instruction pointer pointed to the location of the function, the function executes then all values are popped off of the stack!

If your function is a large complex algorithm which only gets executed a couple of times in the program, and needs keeping seperate for clarity, then this is not such a problem. However if your function is small and gets called repeatedly throughout the program, function inlining allows those few lines of code, to replace the original call to the function. For example,

Without function inlining…

void go()
{
    cout << "Hello World";
    cout << "Test function!";
}
int main()
{
    for(int i( 0);i<10;++i)
    {
        go(); // Standard call mechanism initiated
    }
}

With function inlining enforced…..

inline void go()
{
    cout << "Hello World";
    cout << "Test function!";
}
int main()
{
    for(int i( 0);i<10;++i)
    {
        cout << "Hello World"; //Gets inserted at compile time
        cout << "Test function!"; //Gets inserted at compile time
    }
}

Although many factors contribute towards the performance of a program, inlining can be used to bring about significant performance increases if used properly.

Advertisements

Author: tomtech999

I have recently graduated with a 1st class degree in MComp Games Software Development at Sheffield Hallam University, focusing primarily on application development in C++, with experience in graphics programming, scripting languages, DVCS/VCS and web technology. In my spare time I enjoy Drumming, Reading and Snowboarding!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s