C++ Inline – Why Bother With the ‘inline’ Keyword in C++?

c++compiler-optimizationinline

I've just been researching the use and benefits/pitfalls of the C++ keyword inline on the Microsoft Website and I understand all of that.

My question is this: if the compiler evaluates functions to see if inlining them will result in the code being more efficient and the inline keyword is only a SUGGESTION to the compiler, why bother with the keyword at all?

EDIT: A lot of people are moaning about my use of __inline instead of inline. I'd like to point out that __inline is the Microsoft specific one: so it's not wrong, it's just not necessarily what you're used to. (Also fixed the website link)

EDIT2: Re-formatted the question to indicate the inline keyword (used across all of C++) instead of the Microsoft-specific __inline keyword.

Best Answer

Firstly, it is not __inline, but inline.

Secondly, the effect inline has within the One Definition Rule is undeniably significant. It allows you to define the functions multiple times and have the compiler to handle it.

Thirdly, with regard to the actual inilining this is your way to express your opinion about that function not only to the compiler but also to those who might read your code later. In many cases it is a way to let off the steam, so to say. Basically, it is a way for you to tell the others and yourself: "I feel that this function is too small (or too specialized) to justify the calling overhead, so don't hold me responsible for this travesty. I did all I could. If not for your stupid company-wide coding standard, I would've made it a macro". In that regard it is a sort of formalized comment.

Fourthly, seeing that you used an implementation-specific spelling of the keyword, I'd note that some implementations offer you alternative keywords that give you the opportunity to be more... er... persuasive in your desire to have that function inlined. In MS compiler that would be __forceinline.