inline and macro

Source: Internet
Author: User

The inline function, as an additional feature in C + +, is more reliable than the macro (#define) in traditional C (at least error-prone) when it is necessary to write functional code for a short, similar function.

    #define SQUARE(X) X*X

The working mechanism of a macro is "character substitution."

    a = SQUARE(5.0);   // a = 5.0*5.0    b = SQUARE(4.57.5);   // b = 4.5 + 7.5 * 4.5 + 7.5    c = SUQARE(d++);   // c = d++ * d++;

In these three cases, only the a = SQUARE(5.0); conventional design intent is met. Although you can avoid some problems by adding "()".

    #define SQUARE(X) ((X) * (X))

There is still a problem. Because the macro's parameters are not "value passing". c = SQUARE(d++);will still cause "d++" to execute two times, which may be different from conventional assumptions.

Therefore, if you need to write a macro similar to a function, consider using the C + + inline function instead.

inline and macro

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.