The magical usage of "#" and "# #" in C + + macro definition

Source: Internet
Author: User
Tags define definition

In C + + development often used in the definition of macro use "#" or "# #", the following is a simple description of the use of two symbols:

Define in the # is to use the argument after the # as a symbol, simply to connect it as a string, # #连接前后2个符号, the define definition in the beginning of the "#" macro substitution is not expanded, the macro beginning with the non-# expansion and replace.

As follows:

#define F (A, b) a# #b

#define D (a) #a

#define S (a) d (a)

Puts (d (f (b))); Output result: F (A, B)

Puts (S (f (b))); Output Result: AB

The process is expanded as follows:

Puts (d (f (b))); ----> because the definition of the D macro begins with #, the parameter in the macro is another macro with # #, so the macro as a parameter does not expand, equivalent to puts (#f (A, A, b));----->puts ("f (A, b)");

Puts (S (f (b))); ----> because the definition of S macro does not start with #, the argument in the macro is another macro, but without # #, so the macro as a parameter expands first, equivalent to

Puts (S (AB)),----->puts (d (AB)),---->puts (#ab),---->puts ("AB");

In summary there are the following 2 cases: 1. Do not start with "#", expand Parameter A, and then replace the code:

Puts (S (f (b)))-->puts (S (AB))-->puts (d (AB))-->puts ("AB")

2. Start with "#", replace directly, do not expand:

Puts (d (f (a)))-->puts ("F (A, b)")

The magical usage of "#" and "# #" in C + + macro definition

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.