原来一直对带参的宏有一种畏惧的心理,感觉头大,可能是年龄太小,呵呵,有时候只要过些时间看看自然就懂了,想想也不过如此!

下面这个例子是C Primer Plus上的一个例子,注释部分就是宏展开,其实书中说的很清楚了,宏展开是在预编译的时候,也就是说纯粹是替换,人家也说了叫宏替换。预编译跟什么计算没什么关系,完全是处理一些锁事,所以原来的烦恼不算是什么烦恼,完全是庸人自扰! 

 
  
  1. printf("the result is %d\n", ++y*++y);  //结果是36 

上面这个有点意思,打印出来的不是所想的30,而是36,说是和具体的编译器有关,这个地方只能先记住了:避免在宏中使用自增或自减!等学编译原理的时候再具体研究一下,留个疑问!

 
  
  1. // mac_arg.cpp : Defines the entry point for the console application.  
  2. //  
  3.  
  4. #include<stdio.h>  
  5. #define SQUARE(X) X*X  
  6. #define PR(X) printf("the result is %d\n", X);  
  7.  
  8. int main(int argc, char* argv[])  
  9. {  
  10.     int y = 4;  
  11.     int z;  
  12.  
  13.     printf("y = %d\n", y);  
  14.     z = SQUARE(y);  
  15.     printf("Evaluating SQUARE(y): ");  
  16.     PR(z);  
  17.     /*   
  18.      * printf("y = %d\n", y);  
  19.      * z = y*y;  
  20.      * printf("Evaluatling SQUARE(y): ");  
  21.      * printf("the result is %d\n", z);  
  22.     */ 
  23.  
  24.     z = SQUARE(2);  
  25.     printf("Evaluation SQUARE(2): ");  
  26.     PR(z);  
  27.     /*  
  28.      * z = 2*2;  
  29.      * printf("Evaluation SQUARE(2): ");  
  30.      * printf("the result is %d\n", z);  
  31.      */ 
  32.  
  33.     printf("Evaluation SQUARE(y+2): ");  
  34.     PR(SQUARE(y+2));  
  35.     /*  
  36.      * printf("Evaluation SQUARE(y+2): ");  
  37.      * printf("the result is %d\n", y+2*y+2);  
  38.      */ 
  39.  
  40.     printf("Evaluation 100/SQUARE(2): ");  
  41.     PR(100/SQUARE(2));  
  42.     /*  
  43.      * printf("the result is %d\n", 100/SQUARE(2));  
  44.      * printf("the result is %d\n", 100/2*2);  
  45.      */ 
  46.  
  47.     printf("y = %d\n", y);  
  48.     printf("Evaluaion SQUARE(++y): ");  
  49.     PR(SQUARE(++y));  
  50.     printf("After incrementing, y is %d.\n", y);  
  51.     /*  
  52.      * printf("y = %d\n", y);  
  53.      * printf("Evaluation SQUARE(++y): ");  
  54.      * printf("the result is %d\n", ++y*++y);  
  55.      * printf("After incrementing, y is %d.\n", y);  
  56.      */ 
  57.       
  58.     return 0;  
  59. }  
  60.