C Language macro Definition

Source: Internet
Author: User

C Language macro Definition
1. Examples are as follows:
#define PRINT_STR (s) printf ("%s", S.c_str ())
String str = "ABCD";
Print_str (STR);
The results are as follows: ABCD
2, now I expect to print out, STR=ABCD, easy to think of the solution is:
#define PRINT_STR (s) printf ("s" "=" "%s", S.c_str ())
Print out the result is S=ABCD, not what we expected, think about, why?
In this case, the compiler does not assume that S is the "s" in front of s, and does not replace it. If the substitution is made, then "%s" is replaced by "%str", which is obviously wrong.
3, how to solve the above problem? Use another way, that is, # (string substitution, preceded by double quotes), as follows:
#define PRINT_STR (s) printf (#s "=" "%s", S.c_str ())
It can be thought that for #s, the compiler replaces s with double quotes around s

4, consider the following situation,
int token8 = 102;
Print_token (8);
Expect to print out Token8, the easy-to-think solution is:
#define Print_token (d) printf ("%d", tokend)
This is obviously wrong, the compiler thinks that Tokend is a whole, can not only replace D, how to solve?
5, how to solve this problem? To replace, d must be isolated, and once isolated, the substitution is possible, but cannot be combined with tokens to form a variable.
This is going to use # # (macro connector), you can think of # # to Split, after the split, replace, then the # #去除, as follows:
#define Print_token (d) printf ("%d", token# #d)

6, a # string substitution, two # macro connector

C Language 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.