1.错误写法示范(用值传参),函数内为临时变量,只在{}内有作用,即swap函数内的变化影响不了main函数。
2.用地址传值(用址传参)
3.用异或符号,类似于“负负得正”。
ps:可以观察结果,会发现m,n地址的规律!(最下面有截图)
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
//错误交换
/*void swap(int m,int n)
{
int t;
t=m;
m=n;
n=t;
printf("swaping: %d and %d.\n",m,n);
}//t,m,n这三个临时变量只在此{}有意义!故这种写法是错误的!
int main()
{
int m,n;
printf("please input two numbers:\n");
scanf("%d%d",&m,&n);
printf("before: %d and %d.\n",m,n);
swap(m,n);
printf("after: %d and %d.\n",m,n);
return 0;
}*/
//正确交换(函数)
void swap1(int* m, int* n)
{
int t;
t = *m;
*m = *n;
*n = t;
printf("swaping numerical value: %d and %d.\n", *m, *n);
printf("swaping site: %d and %d.\n", m, n);
}
void swap2(int* m, int* n)//异或符号^
{
*m = *m ^ *n;
*n = *m ^ *n;//*m^*n*^*n=*m;
*m = *m ^ *n;
printf("swaping numerical value: %d and %d.\n", *m, *n);
printf("swaping site: %d and %d.\n", m, n);
}
int main()
{
int m, n;
printf("please input two numbers:\n");
scanf("%d%d", &m, &n);
printf("before: %d and %d.\n", m, n);
printf("before: %d and %d.\n", &m, &n);
swap1(&m, &n);
swap2(&m, &n);
//swap3(&m,&n);
//swap4(&m,&n);
printf("after: %d and %d.\n", m, n);
printf("after: %d and %d.\n", &m, &n);
return 0;
}