码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2016-03-08 00:26:44      阅读:213      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!