CPP C++ Inline Functions

C++ Inline Functions

  • C++ inline function is powerful concept that is commonly used with classes.
  • If a function is inline, the compiler places a copy of the code of that function at each point where the function is called at compile time.
  • To inline a function, place the keyword inline before the function name and define the function before any calls are made to the function.
  • The compiler can ignore the inline qualifier in case defined function is more than a line.
  • Any change to an inline function could require all clients of the function to be recompiled because compiler would need to replace all the code once again otherwise it will continue with old functionality.
  • A function definition in a class definition is an inline function definition, even without the use of the inline specifier.

Syntax:

inline return-type function-name(arguments)
{
   return ( conditions );
}

Following is an example, which makes use of inline function to return max of two numbers:

Example:

#include <iostream>
 

inline int Max(int x, int y)
{
   return (x > y)? x : y;
}

// Main function for the program
int main( )
{

   cout << "Max (30,40): " << Max(30,40) << endl;
   cout << "Max (0,100): " << Max(0,100) << endl;
   cout << "Max (700,10): " << Max(700,10) << endl;
   return 0;
}

Output:

Max (30,40): 40
Max (0,100): 100
Max (700,10): 700

 



Share This Page to Download:

Share to Download

Share This Page on:


Ask Question