Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Benefits of declaring a function as "inline"?

Every time I read about the "inline" declaration in C it is mentioned that it is only a hint to the compiler (i.e. it does not have to obey it). Is there any benefit to adding it then, or should I just rely on the compiler knowing better than me?

like image 780
Sam Avatar asked Dec 09 '09 18:12

Sam


People also ask

What is the benefit of using an inline function?

Inline functions provide following advantages: 1) Function call overhead doesn't occur. 2) It also saves the overhead of push/pop variables on the stack when function is called. 3) It also saves overhead of a return call from a function.

What is advantage of an inline function over macro?

Inline functions are sometimes more useful than macros, as they are safe to use, but can also reduce function call overhead. The inline keyword is a request to the compiler, certain functions won't be inlined like: large functions. functions having too many conditional arguments.

Why is inline function faster?

Inline functions are faster because you don't need to push and pop things on/off the stack like parameters and the return address; however, it does make your binary slightly larger.


1 Answers

There are two reasons to use the inline keyword. One is an optimization hint, and you can safely ignore it; your compiler is like to ignore it too. The other reason is to allow a function to exist in multiple translation units, and that usage is strictly necessary. If you put a function into a .h header file for example, you'd better declare it inline.

like image 124
Mark Ransom Avatar answered Sep 21 '22 05:09

Mark Ransom