Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of an "inline" function definition? [duplicate]

Tags:

c++

Possible Duplicate:
Benefits of inline functions in C++?

What is the difference between

#include <iostream>
using namespace std;
int exforsys(int);
void main( )
{
        int x;
        cout << "n Enter the Input Value: ";
        cin>>x;
        cout << "n The Output is: " << exforsys(x);
}

int exforsys(int x1)
{
        return 5*x1;
}

and

#include <iostream>
using namespace std;
int exforsys(int);
void main( )
{
        int x;
        cout << "n Enter the Input Value: ";
        cin>>x;
        cout << "n The Output is: " << exforsys(x);
}

inline int exforsys(int x1)
{
        return 5*x1;
}

these two definition is work same for a code I guess, then what's the advantage of using the inline function definition?

like image 870
user1532043 Avatar asked Dec 04 '22 00:12

user1532043


2 Answers

The inline keyword suggests to the compiler that the function be inlined. Normally, when a function is called, the current contents of the registers are pushed (copied) to memory. Once the function returns, they are popped (copied back).

This takes a little time, though normally so little that whatever the function does dwarfs the function call overhead. Occasionally when a very small function is called thousands of times per second in a tight loop, the combined function call overhead of all those function calls can add up. In these cases, a programmer can suggest to the compiler that, rather than call the function in that loop, that the contents of the function be put in the loop directly. This avoids the overhead.

Some compilers, notably Microsoft Visual C++, ignore the inline keyword. Microsoft believes their optimizer is smart enough to know when it should inline a function. For those cases when you really want a function to be inlined, Microsoft and other vendors sometimes provide a proprietary, "no, I really mean it!" keyword. In the case if Visual C++, it's __forceinline if I remember right. Even this, however, still can be ignored if the optimizer feels very strongly that inlining that function is a bad idea.

like image 152
Charles Burns Avatar answered Dec 22 '22 00:12

Charles Burns


Since compilers got smart enough to decide which functions would benefit from being inlined and which wouldn't, inline only real effect is to change the function linkage. By default, inline functions have external linkage.

The inline keyword is just a suggestion to the compiler. The compiler could decide to inline functions not declared inline, or to not inline functions declared inline.

like image 30
K-ballo Avatar answered Dec 21 '22 22:12

K-ballo