C语言参数传递

// Paramter_1.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <stdlib.h>
#include <iostream>
using namespace std;
void swap_value(int i,int j){//传值调用
	int temp;
	temp=i;i=j;j=temp;
}
void swap_pointer(int *p,int *q){//传址调用
	int temp;
	temp=*p;*p=*q;*q=temp;
}
void swap_quote(int &x,int &y){///传引用调用
	int temp;
	temp=x;x=y;y=temp;
}
int _tmain(int argc, _TCHAR* argv[])
{

	int a[5]={0,1,2,3,4};

	//swap_value(a[0],a[1]);
	//for(int i=0;i<5;i++){
	//	cout<<a[i]<<" ";
	//} //0 1 2 3 4 请按任意键继续. . .

	//swap_pointer(a[0],a[1]);//错误,int类型的实参与int*类型的形参不兼容
	//swap_pointer(&a[0],&a[1]);////注意:这里一定要是&a[0],表示把a[0]的地址传给了*p,表示*p=&a[0],
	//for(int i=0;i<5;i++){
	//	cout<<a[i]<<" ";
	//}///1 0 2 3 4 请按任意键继续. . .

	swap_quote(a[0],a[1]);
	for(int i=0;i<5;i++){
		cout<<a[i]<<" ";
	}///1 0 2 3 4 请按任意键继续. . .

	system("pause");
	return 0;
}

引用理解起来很简单:


引用(Reference)是C++相对于C语言的又一个扩充。引用类似于指针,只是在声明的时候用 & 取代了 *。引用可以看做是被引用对象的一个别名,在声明引用时,必须同时对其进行初始化。引用的声明方法如下:
类型标识符 &引用名 = 被引用对象
[例1]C++引用示例:
int a = 10;
int &b = a;
cout<<a<<" "<<b<<endl;
cout<<&a<<" "<<&b<<endl;
在本例中,变量 b 就是变量 a 的引用,程序运行结果如下:
10 10
0018FDB4 0018FDB4


从运行结果可以看出,变量 a 和变量 b 都是指向同一地址的,也即变量 b 是变量 a 的另一个名字,也可以理解为 0018FDB4 空间拥有两个名字:a和b。由于引用和原始变量都是指向同一地址的,因此通过引用也可以修改原始变量中所存储的变量值。

你可能感兴趣的:(C语言,参数传递,函数参数)