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