The C + + language new keyword, inline, is used to declare a function as an inline function. At program compile time, the compiler replaces the inline function call with the body of the function, which is similar to the macro extension in the C language.
The use of inline functions can effectively avoid the overhead of function calls, and program execution is more efficient. The disadvantage of using inline functions is that if the body of the function declared as an inline function is very large, the executable code of the compiler will become large. In addition, if there is a loop or other complex control structure in the function body, it takes much longer to deal with these complex control structures than the time spent by function calls, so if you declare such a function as an inline function, it is not very meaningful, but it can make the compiled executable code grow longer.
Usually during the programming process, we declare some short functions that are frequently called as inline functions.
In order for the inline declaration inline function to work, we must put the inline keyword together with the function body, or the inline keyword cannot successfully declare the function inline. As shown in Example 1, the inline keyword has no effect, while example 2 succeeds in declaring the swap function as an inline function.
[Example 1] The inline keyword does not work at the function declaration:
inline void swap (int &a, int &b);
void swap (int &a, int &b)
{
int temp = A;
A = b;
b = temp;
}
[Example 2] The inline keyword should be put together with the function body:
void swap (int &a, int &b);
inline void swap (int &a, int &b)
{
int temp = A;
A = b;
b = temp;
}
C + + learning 6-inline functions