0%

C语言实现交换

这里介绍两种方式,一种是通过宏定义的方式实现,一种是通过指针交换实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <stdio.h>;

#define swap_m(x, y, t) ((t)=(x),(x)=(y),(y)=(t))

void swap(int *x, int *y);

int main()
{
int a = 10;
int b = 1;
int temp;
swap(&amp;a, &amp;b);
printf(&quot;a=%d, b=%d\n&quot;, a, b);
swap_m(a, b, temp);
printf(&quot;a=%d, b=%d\n&quot;, a, b);
return 0;
}

void swap(int *x, int *y)
{
int tmp;
tmp = *x;
*x = *y;
*y = tmp;
}

Welcome to my other publishing channels