Inline Function

◀ Function Pointer▶ Operator Overloading
Amazon Inline functions are a C++ feature designed to make programs run faster. Normal function calls have the program jump to another address and then return when the function finishes executing. Inline functions, however, make compiler replace their function calls with the actual function code. This way, the program does not have to jump to another location to execute code and then jump back, thereby increasing speed of running a program.

The downside, obviously, is that the executable code is bigger because there are as many copies of function code as the number of function calls. Also, the speed gain usually is minimal, so you probably do not see any improvement anyway.


In general, the best way to take advantage of inline functions is to make very short, frequently used functions inline.
To use this feature, you need to prefix the keyword inline to the function definition. Here is a sample program illustrating the inline feature:
#include<iostream>
using namespace std;
#include<ctime> 	/* or <time.h> */

inline double square(double x) { return x*x; }

int main(){
double i,j,k,temp; int limit = 100; clock_t start = clock(); for(i=0;i<limit;i+=0.5) for(j=0;j<limit;j+=0.5) for(k=0;k<limit;k+=0.5) temp=square(k); cout << (float)(clock() - start) / CLOCKS_PER_SEC << " seconds\n"; return 0; }
You can run this version several times, then take out the word “inline”, then run the modified version several times. I ran this experiment and here is what I got:
With inline (in seconds)Without inline (in seconds)
0.5370.633
0.5060.964
0.5380.871
As you can see, proper use of inline functions does pay off in terms of program speed. Incidentally, C uses #define statement to provide the functionality of an inline function. For example, to get the product of two numbers, you do:

#define product(a,b) a*b
During compiling, the compiler substitutes a*b for every occurrence of product(a,b). If you do:
int i = product(3+4,4+5);
product(3+4,4+5) will be replaced with 3+4*4+5, yielding undesired results. Thus, it is generally advisable for you to use C++ inline functions.

Also, any function defined in the class declaration becomes an inline function automatically. You still can make a function defined outside the class declaration an inline function by prefixing it with the keyword inline.

◀ Function Pointer▶ Operator Overloading

fShare
Questions? Let me know!