I am studying macros and found many sources and questions regarding difference between macros and inline functions. But there is nothing which concretely specifies and differentiates pros&cons of inline vs normal functions.
But what about if I want to select between normal function and inline function?
I know that use of inline function increase the code size. But as while studying size is not the primary issue , efficiency is the goal. Making a function an inline function suggests that calls to the function be as fast as possible.(Due to stack and stuff overhead)
Is always using inline function is better or not? If not then WHY? What are the benefits of using normal functions over inline?
While reading other questions I read that inline is only a hint to compiler. Compiler may ignore it. When does compiler ignore it and WHY?
Inlining a function can have several advantages:
It can make the program size smaller. This is typically the case when a function is only used once. Also, see 2. and 3.
The compiler can eliminate unused bits of the function, if the compiler knows that a variable is constant, or non-NULL, or something like that. This can save size, but also makes the code more efficient at run time.
The compiler can eliminate bits of the calling function, or even other inlined functions because it can see what the function does with/to the data. (Say the code checks the return value and calls an error function if it's NULL, it might be able to rule that out.
It can reduce the call overhead, but in current processors with predictive branching that's not as much of a win as you might think.
It can hoist constant bit out of loops, do common subexpression elimination, and many other optimizations to make looping code more efficient, and such like.
And then there's the disadvantages:
It can make the code larger, obviously.
It can increase register pressure within the calling function which might confuse the compiler and prevent it optimizing as well.
Having one hot function that can live in the CPU cache can be quicker than duplicating it to many places that are not always cached.
It can hamper debugging.
The reason that the inline function is just a hint is mostly because the C standard does not require that the compiler optimize anything at all. If it wasn't a hint then optimization wouldn't be optional. Also, just because the function isn't marked inline doesn't stop the compiler inlining it if it calculates that doing so would be advantageous.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With