Click here to Skip to main content
15,072,691 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I was learning about inline functions and i had two questions in my mind.

1: inline functions are used when you have a small function called often in your program, but I don't understand what is considered a small function. Is it a function with 2 lines of code or less? Please explain to me what makes a function small.

2: small functions are said to use more overheads and as a result inline functions were the solution, but why and how do small functions have more overhead.

What I have tried:

I have tried researching but nothing useful comes up
Posted
Updated 20-Jun-21 0:37am

1 solution

The original purpose of inline functions was what you stated, but they're not used that way anymore.

The original idea was that a function tagged inline would not actually be called when the compiler generated code. Instead, the compiler would copy its code in line, executing it within whatever function was "invoking" the inline function. This would save the overhead of a function call and return, and possibly having to push arguments onto the stack, create a stack frame and destroy it, and whatever other code was generated for a function call. Any function could be tagged inline; whether the compiler obeyed, by doing what I just described, was up to it. The trade-off was faster code at the cost of a larger executable, given that the function's code was cloned to each place were it was invoked. And if the inlined function had a bug, fixing it (assuming that the system had a patching capability) was painful because of all these clones.

These days, compilers are so good at optimizing code that they take it upon themselves to inline functions. In fact, they do it to the point where it's very difficult to debug an executable that has been aggressively optimized. So, functions are no longer tagged inline for this purpose.

The meaning of inline has therefore changed. Or, more accurately, only retains part of its original meaning. You can read a rather arcane explanation here[^]. A good example of what it means is that I use inline in a class template to tag a function that does not use the template parameter (e.g. <T>) and can therefore be shared by all instantiations of the template. If this makes no sense to you, don't worry. If you work with C++ long enough, it eventually will. :)
   
v2
Comments
Richard MacCutchan 20-Jun-21 7:18am
   
"If you work with C++ long enough, it eventually will (make sense)"
Well after nearly 30 years of it I am still struggling. :(

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900