内容概要
一、函数的传参都是值传入
#include <stdio.h>void swap(int,int);void swap(int x, int y){int temp; printf("in swap x:%d , y:%d\n", x, y); temp = x; x = y; y = temp; printf("in swap x:%d , y:%d\n", x, y); }int main(){int x = 3, y = 5; printf("in main x:%d , y:%d\n", x, y); swap(x,y); printf("in main x:%d , y:%d\n", x, y); return 0; }
执行结果
in main x:3 , y:5in swap x:3 , y:5in swap x:5 , y:3in main x:3 , y:5
使用指针传入地址,而不是单纯传入值
#include <stdio.h>void swap(int,int);void swap(int *x, int *y){int temp; printf("in swap x:%d , y:%d\n", *x, *y); temp = *x;*x = *y;*y = temp; printf("in swap x:%d , y:%d\n", *x, *y); }int main(){int x = 3, y = 5; printf("in main x:%d , y:%d\n", x, y); swap(&x,&y); printf("in main x:%d , y:%d\n", x, y); return 0; }
执行结果
in main x:3 , y:5in swap x:3 , y:5in swap x:5 , y:3in main x:5 , y:3