Inline function

Though inline functions are not that necessary, but we use them to make our program faster.

Normally, when we call a function, the function first gets called and then its body gets executed. It takes comparatively more time to call a function than to write the code in the program in place of that function call.

We are doing the same thing in both the above programs i.e., calculating the sum of two variables 'a' and 'b'. In the second program, we first called the function 'sum()' which then calculated the sum as x + y and returned it. On the other hand in the first program, we directly printed the expression for sum a + b in the main program. So in the first case, we saved the time of calling the function.

So, if we had to choose one of the above methods to print the sum of two numbers, we would choose the first case which would make our program run faster.

Now, suppose we have to print the sum of many such sets of numbers. Then writing the expression (a+b) would be hectic. Things will become worse if the expression is more complex.

This is when the need of inline function arises.

Inline function works same as the first case where we do not need to call any function. In a program, wherever a function declared as inline is called, the compiler will replace the function call with the code in the function. This saves the time that is taken when calling a function ( as in the second case ) as well as it prevents us from writing the same code again and again ( as in the first case ).

To make a function inline, we need to write the keyword inline before the function name.

Here, we declared the function sum() as inline. So, when this function is called in the main class, the compiler replaces this function call sum(a, b) with the code in the body of the function 'sum()'. So, the above code becomes as shown below: