What is Inline function in C++ ?

Inline function

C++ provides an inline function to reduce the function call overhead. Inline function is a function that is expanded in line when it is called. When the inline function is called whole code of the inline function gets inserted or substituted at the point of inline function call. This substitution is performed by the C++ compiler at compile time. Inline function may increase efficiency if it is small. The syntax for defining the function inline is:

inline return-type function-name(parameters)

{

    // function code

Example of inline function

#include <iostream.h>

#include <conio.h>

inline int cube(int s)

{

    return s*s*s;

}

int main()

{

    cout << "The cube of 3 is: " << cube(3) << "\n";

    return 0;

}

Output: The cube of 3 is: 27

 

Inline functions provide following advantages:
1) It saves the overhead of push/pop variables on the stack when function is called.
2) It also saves overhead of a return call from a function.
4) Inline function may be useful (if it is small) for embedded systems because inline can yield less code than the function call preamble and return.

Default argument

When define a function, can specify a default value for each of the last parameters. This value will be used if the corresponding argument is left blank when calling to the function. This is done by using the assignment operator and assigning values for the arguments in the function definition. If a value for that parameter is not passed when the function is called, the default given value is used, but if a value is specified, this default value is ignored and the passed value is used instead. Consider the following example:

 

#include <iostream>

using namespace std;

intadd(int a, int b=20)

 {

int result;

result = a + b;

return (result);

}

int main () {

   // local variable declaration:

int a = 100;

int b = 200;

int result;

   // calling a function to add the values.

result = add(a, b);

cout<< "Total value is :" << result <<endl;

 

   // calling a function again as follows.

result = add(a);

cout<< "Total value is :" << result <<endl;          

return 0;

}

When the above code is compiled and executed, it produces the following result:

Total value is: 300

Total value is: 120

Post a Comment

Thankyou

Previous Post Next Post