1.宏(macro)
1.1定义宏
#define macro body example: #define PI 3.14 //object-like macro #define SQUARE(x) ((x)*(x)) //function-like macro
1.2预处理器不进行计算,而只进行字符串替换。比如,对于x*x用x+2替换x则会得到x+2*x+2.
1.3#运算符
如果x是一个宏参量,那么#x可以把参数名转化为相应字符串。该过程称为字符串化(stringizing)。
#include <stdio.h> #define PSQR(x) printf("The square of " #x " is %d.\n",((x)*(x))) int main(void) { int y = 5; PSQR(y); PSQR(2 + 4); return 0; } Here’s the output: The square of y is 25. The square of 2 + 4 is 36.
1.4##运算符
这个运算符可以把两个token组合成单个token。
#define XNAME(n) x ## n Then the macro XNAME(4) would expand to the following: x4
1.5Here are some points to note:
■ Remember that there are no spaces in the macro name, but that spaces can appear in the replacement string. ANSI C permits spaces in the argument list.
■ Use parentheses around each argument and around the definition as a whole. This ensures that the enclosed terms are grouped properly in an expression such as forks = 2 * MAX(guests + 3, last);
■ Use capital letters for macro function names. This convention is not as widespread as that of using capitals for macro constants. However, one good reason for using capitals is to remind yourself to be alert to possible macro side effects.
■ If you intend to use a macro instead of a function primarily to speed up a program, first try to determine whether it is likely to make a significant difference. A macro that is used once in a program probably won’t make any noticeable improvement in running time. A macro inside a nested loop is a much better candidate for speed improvements. Many systems offer program profilers to help you pin down where a program spends the most time.