原来一直对带参的宏有一种畏惧的心理,感觉头大,可能是年龄太小,呵呵,有时候只要过些时间看看自然就懂了,想想也不过如此!
下面这个例子是C Primer Plus上的一个例子,注释部分就是宏展开,其实书中说的很清楚了,宏展开是在预编译的时候,也就是说纯粹是替换,人家也说了叫宏替换。预编译跟什么计算没什么关系,完全是处理一些锁事,所以原来的烦恼不算是什么烦恼,完全是庸人自扰!
- printf("the result is %d\n", ++y*++y); //结果是36
上面这个有点意思,打印出来的不是所想的30,而是36,说是和具体的编译器有关,这个地方只能先记住了:避免在宏中使用自增或自减!等学编译原理的时候再具体研究一下,留个疑问!
- // mac_arg.cpp : Defines the entry point for the console application.
- //
- #include<stdio.h>
- #define SQUARE(X) X*X
- #define PR(X) printf("the result is %d\n", X);
- int main(int argc, char* argv[])
- {
- int y = 4;
- int z;
- printf("y = %d\n", y);
- z = SQUARE(y);
- printf("Evaluating SQUARE(y): ");
- PR(z);
- /*
- * printf("y = %d\n", y);
- * z = y*y;
- * printf("Evaluatling SQUARE(y): ");
- * printf("the result is %d\n", z);
- */
- z = SQUARE(2);
- printf("Evaluation SQUARE(2): ");
- PR(z);
- /*
- * z = 2*2;
- * printf("Evaluation SQUARE(2): ");
- * printf("the result is %d\n", z);
- */
- printf("Evaluation SQUARE(y+2): ");
- PR(SQUARE(y+2));
- /*
- * printf("Evaluation SQUARE(y+2): ");
- * printf("the result is %d\n", y+2*y+2);
- */
- printf("Evaluation 100/SQUARE(2): ");
- PR(100/SQUARE(2));
- /*
- * printf("the result is %d\n", 100/SQUARE(2));
- * printf("the result is %d\n", 100/2*2);
- */
- printf("y = %d\n", y);
- printf("Evaluaion SQUARE(++y): ");
- PR(SQUARE(++y));
- printf("After incrementing, y is %d.\n", y);
- /*
- * printf("y = %d\n", y);
- * printf("Evaluation SQUARE(++y): ");
- * printf("the result is %d\n", ++y*++y);
- * printf("After incrementing, y is %d.\n", y);
- */
- return 0;
- }
转载于:https://blog.51cto.com/01051192/593435