函数参数的传递
1、值传递:test01(int a,int b)
实现了将实参赋值给形参的操作,但是未对实参进行操作,所以只是改变了形参的值,实参的值没有改变。
举例:
void test01(int a,int b){
int temp = a;
a = b;
b = temp;
printf("a = %d,b = %d",a,b);
}
int main(){
int x = 4;
int y = 6;
test01(x,y);
printf("x = %d,y = %d",x,y);
return 0;
}
//a = 6,b = 4;
//x = 4,y = 6;
2、地址传递:test02(int *a,int *b)
实现的是将形参的地址给实参,实质上是对实参进行了操作,形参和操作同时发生了改变。
举例:
void test02(int *a,int *b){
int temp = *a;
*a = *b;
*b = temp;
printf("a = %d,b = %d",*a,*b);
}
int main(){
int x = 4;
int y = 6;
test01(&x,&y);
printf("x = %d,y = %d",x,y);
return 0;
}
//a = 6,b = 4;
//x = 6,y = 4;
3、引用传递:test03(int &a,int &b)
实现的是把实参给到形参,实质上是对实参做出来了改变,所以实参和形参都发生改变了。
举例:
void test03(int &a,int &b){
int temp = a;
a = b;
b = temp;
printf("a = %d,b = %d",a,b);
}
int main(){
int x = 4;
int y = 6;
test01(x,y);
printf("x = %d,y = %d",x,y);
return 0;
}
//a = 6,b = 4;
//x = 4,y = 6;