C++ Learning 6-Inline Functions

The C++ language adds the keyword inline to declare a function as an inline function. When the program is compiled, the compiler will replace the inline function call with the function body, which is similar to the macro expansion in the C language.

Using inline functions can effectively avoid the overhead of function calls, and the program execution efficiency is higher. 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 program compiled by the compiler will become very large. In addition, if there are loops or other complex control structures in the function body, the time spent processing these complex control structures at this time is much greater than the time spent in calling the function. Therefore, if such functions are declared as inline functions, it does not make sense. If it is large, it will make the compiled executable code longer.

Usually in the process of programming, we will declare some frequently called short functions as inline functions.

In order to make the inline declaration of the inline function valid, we must put the inline keyword and the function body together, otherwise the inline keyword cannot successfully declare the function inline function. As shown in Example 1, the inline keyword has no effect, while in Example 2, the swap function is successfully declared as an inline function.

[Example 1] The inline keyword does not work in 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 placed with the function body:

void swap(int &a, int &b);
inline void swap(int &a, int &b)
{
    int temp = a;
    a = b;
    b = temp;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325115162&siteId=291194637