//带参数的宏:传入的参数会被粘贴进文本,
//每个参数以及整个结果都要加圆括号
#define SQUARE(x) ((x) * (x))
#define MAX(a, b) ((a) > (b) ? (a) : (b))
int square1 = SQUARE(5);
//square1 is 25
int square2 = SQUARE(2 + 3);
//square2 is 25
double maxValue = MAX(2.5, 1.5);
//maxValue is 2.5
//不加圆括号:2 + 3 * 2 + 3
#define BAD_SQUARE(x) x * x
int square3 = BAD_SQUARE(2 + 3);
//square3 is 11
//参数在文本中用了几次,就粘贴几次:
//这里 i++ 会运行两次
int i = 5;
int maxI = MAX(i++, 0);
//maxI is 6, i is 7
//多条语句放进 do { ... } while (0),
//这样宏在 if 之后才相当于一条语句
#define SWAP(a, b) do { typeof(a) tmp = (a); (a) = (b); (b) = tmp; } while (0)
int x = 1;
int y = 2;
if (x < y)
SWAP(x, y);
//x is 2, y is 1
//不需要宏的地方,函数更安全:
//参数只计算一次,类型也会被检查
int squareInt(int n) {
return n * n;
}
int j = 7;
int square4 = squareInt(j++);
//square4 is 49, j is 8
printf("square1 is %d\n", square1);
printf("square2 is %d\n", square2);
printf("maxValue is %g\n", maxValue);
printf("square3 is %d\n", square3);
printf("maxI is %d\n", maxI);
printf("i is %d\n", i);
printf("x is %d\n", x);
printf("y is %d\n", y);
printf("square4 is %d\n", square4);
printf("j is %d\n", j);