inline functions vs normal functions

user3435894 picture user3435894 · Apr 21, 2014 · Viewed 7.8k times · Source

I am fairly new to C and C++ and I am trying to understand about functions. I came across this term called inline function and understand it as when a function is declared inline, the compiler pastes the entire code in that function whenever and wherever it is called.

I thought this is actually what happens at a function call but now realize that is not the case.

Can someone explain in detail as to what happens at the compiler and system level when a normal function is called and an inline function is called?

Any material on understanding this will be appreciated.

Answer

Mahonri Moriancumer picture Mahonri Moriancumer · Apr 21, 2014

When calling a (non-inline) function, the compiler has to place the function parameters/arguments in a location where the called function will expect to find them. In some cases, it will 'push' the arguments onto the process/thread's stack. In other cases, CPU registers might be assigned to specific arguments. Then, the "return address", or the address following the called function is pushed on the stack so that the called function will know how to return control back to the caller.


When calling an inline function, the compiler simply weaves the function into the code. There is no need for a common protocol between the caller, and called, functions as to where parameters will be placed. A 'return' statement (in the called in-line function), is generally implemented (by the compiler) to jump to the next instruction following the inline code.


An inline function, if called many times in the code, will cause the code size to increase. However, it is generally less expensive (in cpu cycles) to make an inline-call, than to make a function call.