#include <stdio.h>
void swap(int a,int b)
{
int temp=a;
a=b;
b=temp;
}
int main()
{
int a=4,b=5;
swap(a,b);
printf("a = %d ,b = %d\n",a,b);
return 0;
}
交换两个数的值!
很显然无效。
然后我们在函数里面加上打印
#include <stdio.h>
void swap(int a,int b)
{
printf("address in swap():%p %p\n",&a,&b);
int temp=a;
a=b;
b=temp;
}
int main()
{
int a=4,b=5;
printf("address in main():%p %p\n",&a,&b);
swap(a,b);
printf("a = %d ,b = %d\n",a,b);
return 0;
}
可以得出 地址是不同的!
我们知道给一个变量赋值,实际上是向一块地址上写值。
但是 值传递是向函数的参数地址上写值 所以实现数据交换是不行的
还有
用参数是值的函数赋值是行不通的,例如
#include <stdio.h>
int a(int b)
{
b=5;
}
int main()
{
int c=10;
a(c);
printf("c is %d\n",c);
}