一:c语言版本
#include
void swap(int x,int y);
void swap_p(int *px,int *py);
#define swap_m(x,y,t) ((t)=(x),(x)=(y),(y)=(t))
int main(void)
{
int a,b,temp;
a=1;
b=10;
printf("a=%d,b=%dn",a,b);
//swap_p(&a,&b);
swap_m(a,b,temp);
printf("a=%d,b=%dn",a,b);
return 0;
}
void swap(int x,int y)
{
int temp;
temp=x;
x=y;
y=temp;
}
void swap_p(int *px,int *py)
{
int temp;
temp=*px;
*px=*py;
*py=temp;
}
gcc编译后 执行./a.out
[web@ztx dev_local]$ ./a.out
a=1,b=10
a=10,b=1
[web@ztx dev_local]$
二:c++版本
demo1.
#include
using namespace std;
int main()
{
int a, b, tmp;
a = 1;
b = 10;
cout << "a = " << a << ", b = " << b << endl;
tmp = a;
a = b;
b = tmp;
cout << "a = " << a << ", b = " << b << endl;
return 0;
}
demo2.
#include
using namespace std;
void swap(int *px, int *py);
int main()
{
int a,b;
a = 1;
b = 10;
cout << "传指针的方法: " << endl;
cout << "a = " << a << ", b = " << b << endl;
// 拷贝的指针(地址)
swap(&a,&b);
cout << "a = " << a << ", b = " << b << endl;
return 0;
}
void swap(int *px, int *py)
{
int temp;
temp = *px;
*px = *py;
*py = temp;
}