Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

__inline functions vs normal functions in C

Tags:

c

inline

c99

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?

like image 804
Abhishek Gupta Avatar asked Nov 30 '22 06:11

Abhishek Gupta


1 Answers

Inlining a function can have several advantages:

  1. It can make the program size smaller. This is typically the case when a function is only used once. Also, see 2. and 3.

  2. 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.

  3. 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.

  4. 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.

  5. 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:

  1. It can make the code larger, obviously.

  2. It can increase register pressure within the calling function which might confuse the compiler and prevent it optimizing as well.

  3. 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.

  4. 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.

like image 177
ams Avatar answered Dec 05 '22 03:12

ams