C + + learning 6-inline functions

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.