您的位置:首页 > 理论基础 > 计算机网络

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

2016-03-07 23:39 453 查看
  题意要求宏,能交换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);

}


      这是因为大师在书上明确指出宏不是调用函数,而是直接替换文本插入代码中。所以开始的代码中()一起被插入了代码中。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: