c 函数参数(总结)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_40301026/article/details/79393953

函数参数为两种:形式参数和实际参数

1.形式参数

形参出现在被调函数当中,在整个函数体内都可以使用。形参在定义时编译系统并不分配存储空间,只有在调用该函数时才分配内存单元。调用结束内存单元被释放,故形参只有在函数调用时有效,调用结束时不能再使用。

2.实际参数

实参出现在主调函数当中,当函数调用时,主调函数把实参的值传送给被调函数的形参,从而实现函数间的数据传递。传递方式有两种:值传递和地址传递方式。

参数传递:
参数传递首先要搞清楚是 值传递还是地址传递,这是极为重要的。若为值传递是不能改变实际变量的值是单向传递而 地址传递则是双向改变的。

一.值传递:

1. 当形参定义为变量时,实参可以是常量、变量和表达式,这种函数间的参数传递为值传递方式。值传递的特点是参数的“单向传递” 并不会改变a,b的值。
#include<stdio.h>
void myswap(int x, int y)
{
    int t;
    t=x;
    x=y;
    y=t;
}
int main()
{
    int a, b;
    printf("Please enter two integers to be exchanged.:");
    scanf("%d %d", &a, &b);
    myswap(a,b);  //作为对比,直接交换两个整数,显然不行
    printf("The result of calling the exchange function:%d 和 %d\n", a, b);
    return 0;
}

2 .数组元素作为函数参数。
数组元素也为值传递:
int swap(int a,int b)
{
   int temp;
   temp=a;
   a=b;
   b=temp;
   return 0;
}  
int main (void){
		int a[]={3,4};
		swap(a[0],b[0]);
	}
二.地址传递。

1.数组名作为函数参数也传的是地址。
2. 数组指针,即数组元素的地址作为函数参数
int swap(int *a,int *b)
{
   int temp;
   temp=*a;
   *a=*b;
   *b=temp;
   return 0;
}  
int main (void){
		int arr[] = {1,2};
		int *a = &arr[0];
	    	int *b = &arr[1];
			swap(a,b);
	}
3.直接传入地址。
#include<stdio.h>
void myswap(int &x, int &y)
{
    int t;
    t=x;
    x=y;
    y=t;
}

int main()
{
    int a, b;
    printf("Please enter two integers to be exchanged:");
    scanf("%d %d", &a, &b);
    myswap(a,b);  //直接以变量a和b作为实参交换
    printf("The result of calling the exchange function:%d 和 %d\n", a, b);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40301026/article/details/79393953