This is a short article on inline function used in C.
What is inline Function ?
“Inline” Function is a provision or feature provided by the compiler. Inline is a request made to the compiler to replace the inline function call with the function definition.
Inline Function Definition Example:
inline void fun(/*fun argument */)
/* Function source Code */
When a normal function call happens function creates its stack in the main stack and initializes all local variables. After completion of function call return value is given back if any and stack is destroyed. Much time is consumed in stack operation. Hence for Small function Inline function is beneficial as the call is replaced by definition, so no external stack created and operations are much faster for small, commonly-used functions.
it is only useful to make the function inline if the time spent during a function call is more compared to the function body execution time.
*To be clear
macros are managed by pre-processor and inline functions are managed by the compiler.
Will compiler accept all requests to consider a function as inline ?
A compiler may not perform inline operation in the following criteria.
1. If the function is recursive.
2. If function Contain switch case or Loops (for, While)
3. If a function return type is other than void
4. If function Contains Static Variables
Code execution is much faster than a normal function call. For small function call stack, overhead is avoided.
Using too many inline functions increases the size of the binary executable file and compilation time will be more because of duplication of the same code. If the inline function call has local variables so it will increase the variable count in one stack so utilization of CPU register will increase.
Why inline function is being treated as simple function call ?
- The purpose of inline function to put it’s code in calling function. It is primarily used for better speed. But sometime it can be simply treated as a normal function call. It has dependency on compiler implementation and optimization.
- As per GCC online docs
GCC does not inline any functions when not optimizing unless you specify the ‘always_inline’ attribute for the function, like this:
/* Prototype. */
inline void foo (const char) __attribute__((always_inline));
Just write an inline function without always_inline attribute , build it with GCC in Eclipse IDE and test. You may watch disassembly using Window->Show View->Disassembly . You may notice that it is being invoked using simple function call. Repeat the same with attribute always_inline .
Thanks to Vinit Tirnagarwar for his contribution in this article. This helps in understanding the proper use of inline function to write an optimized code.
Would you like to help the student community with quick technical tips ?
Thanks for reading till end. If you liked it, Please share in your network.