看《C程序设计语言》(英文版)学到的两个用法。
两个很简单的宏用法。
#的用法: if, however, a parameter name is preceded by a # in the replacement text, the combination will be expanded into a quoted string with the parameter replaced by the actual argument.
#include <stdlib.h> #define dprint(expr) printf(#expr " = %g\n", expr); int main() { double x = 1.0, y = 2.0; dprint(x/y); return 0; }
结果为 x/y = 0.5
#define dprint(expr) printf(#expr " = %g\n", expr);
When this is invoked, as in
#define dprint(expr) printf(#expr " = %g\n", expr);
the macro is expanded into
printf("x/y" " = %g\n", x/y);
and the strings are concatenated, so the effect is
printf("x/y = %g\n", x/y);
Within the actual argument, each " is replaced by \" and each \ by \\, so the result is a legal string constant.
##的用法: The preprocessor operator ## provides a way to concatenate actual arguments during macro expansion. If a paramter in the replacement text is a adjacent to a ##, the parameter is replaced by the actual argument, the ## and surrouding white space are removed, and the result is re-scanned.
例如:
#include <stdio.h> #include <stdlib.h> #define paste(front, back) front ## back int main() { int x, x1; x = 2, x1 = 3; printf("%d\n", paste(x, 1)); return 0; }
输出结果是3.
#define paste(front, back) front ## back
so paste(x, 1) creates the token x1.