mxwawaawxm 发表于 2019-7-20 22:07

C语言如何定义函数式宏,交换两个变量的值

本帖最后由 mxwawaawxm 于 2019-7-25 19:38 编辑


如图。要求定义一个函数式宏,交换两个变量的值
#define swap(type,a,b)
swap(int,x,y)
请问如何实现

testicles 发表于 2019-7-20 22:28

#define swap(type, a, b) do {      
    type t;
    t = a;
    a = b;
    b = t;
            } while (0);

nbqdbltt 发表于 2019-7-21 00:32

楼上正解。。。。。

mxwawaawxm 发表于 2019-7-21 20:39

testicles 发表于 2019-7-20 22:28
#define swap(type, a, b) do {      
    type t;
    t = a;


试了下不行。
报错
error: unknown type name 'type'; did you mean 'typeof'?
   type t;
   ^~~~
   typeof

#include <stdio.h>

#define swap(type, a, b) do {      
    type t;
    t = a;
    a = b;
    b = t;
} while (0);

int main(void)
{
    int a=5, b=4;
    swap(int, a, b);
    printf("a = %d, b = %d\n", a, b);
    return 0;
}

mxwawaawxm 发表于 2019-7-21 20:40

nbqdbltt 发表于 2019-7-21 00:32
楼上正解。。。。。

试了下。不行。报错如上图所示
https://www.52pojie.cn/forum.php?mod=redirect&goto=findpost&ptid=993267&pid=26979364

testicles 发表于 2019-7-21 21:23

本帖最后由 testicles 于 2019-7-21 21:39 编辑

#define swap(type, a, b) do { \   
    type t; \
    t = a; \
    a = b; \
    b = t; \
            } while (0);

记起来了要加 \
楼主有百度云账号么?能借用下载资料么

mxwawaawxm 发表于 2019-7-21 22:08

testicles 发表于 2019-7-21 21:23
#define swap(type, a, b) do { \   
    type t; \
    t = a; \


谢谢。好像也可以不加do……while循环
至于百度帐号,你试试这两个
都是微博登陆,有效期25天左右,后面有机会持续更新
17176840940    密码pd4327

更新 一个账号密码             17177203450            pd2288         

来源https://www.52pojie.cn/thread-991436-1-1.html

mxwawaawxm 发表于 2019-7-21 22:13

testicles 发表于 2019-7-21 21:23
#define swap(type, a, b) do { \   
    type t; \
    t = a; \


#include <stdio.h>

#define swap(type, a, b) type temp=a; a = b; b = temp;

int main(void)
{
    int a=5, b=6;
    swap(int, a, b);
    printf("%d %d\n", a, b);
    return 0;
}
请问,为什么这样能运行
我换成逗号运算符就不行了
#include <stdio.h>

#define swap(type, a, b) (type temp=a, a=b, b=temp)

int main(void)
{
    int a=5, b=6;
    swap(int, a, b);
    printf("%d %d\n", a, b);
    return 0;
}

8bit 发表于 2019-7-22 00:04

在编译前,编译器会进行预处理,将宏定义展开,也就是按照你的宏定义去替换,使用逗号运算符时,swap(int, a, b)会被替换成int temp=a, a=b, b=temp,这个语法明显是错误的。

testicles 发表于 2019-7-22 08:30

mxwawaawxm 发表于 2019-7-21 22:13
#include

#define swap(type, a, b) type temp=a; a = b; b = temp;


do while 是为了防止如下情形出现错误

if(...)
swap(...);

直接替换就没有大括号,意思就变了

好吧,那个百度云已经限速了
页: [1]
查看完整版本: C语言如何定义函数式宏,交换两个变量的值