首页 > 其他 > 详细

关于tcpl习题4-14定义宏swap(t,x,y)

时间:2016-03-08 00:25:32      阅读:208      评论:0      收藏:0      [点我收藏+]

       题意要求宏,能交换t类型的两个参数。由于愚昧,没读懂题意。于是在网上查到答案:

 

#define SWAP(t,x,y) (t temp;temp = x;x = y;y = temp;)

     虽然懂了意思但用gcc写了个例子编译失败。

 

    

#include<stdio.h>
#define SWAP(t,x,y) (t temp;temp = x;x = y;y = temp;)
#define dprintf(expr) printf(#expr " = %d\n",expo)

main() {
        
   int x = 10;
   int y = 40;
   SWAP(int,x,y) 
   dprintf(x); 
   dprintf(y); 

}

 

    但去掉宏定义中的()就能正确交换xy的值

 

#include<stdio.h>
#define SWAP(t,x,y) t temp;temp = x;x = y;y = temp;
#define dprintf(expr) printf(#expr " = %d\n",expo)

main() {
        
   int x = 10;
   int y = 40;
   SWAP(int,x,y) 
   dprintf(x); 
   dprintf(y); 

}

      这是因为大师在书上明确指出宏不是调用函数,而是直接替换文本插入代码中。所以开始的代码中()一起被插入了代码中。

关于tcpl习题4-14定义宏swap(t,x,y)

原文:http://www.cnblogs.com/xiaozhang1991/p/5252460.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!