Example of function reference, pointer transfer, value transfer, and analysis

# include<iostream>
using namespace std;
void ar(int & a, int & b); //引用传递 
void ap(int * p, int * q); //指针传递 
void av(int a, int b); //值传递 
int main()
{
	int value1 = 100;
	int value2 = 200;
	cout << "value1 = " << value1;
	cout << "value2 = " << value2 << endl;
	cout << "引用传递" << endl;
	ar(value1, value2);
	cout << "value1 = " << value1;
	cout << "value2 = " << value2 << endl;
	cout << "指针传递" << endl;
	ap(&value1, &value2);
	cout << "value1 = " << value1;
	cout << "value2 = " << value2 << endl;  
	cout << "值传递" << endl;
	av(value1, value2);
	cout << "value1 = " << value1;
	cout << "value2 = " << value2 << endl;    
	
	return 0;
}
void ar(int & a, int & b) //引用传递 
{
	int t;
	t = a;
	a = b;
	b = t;
}
void ap(int * p, int * q) //指针传递 
{
	int t;
	t = *p;
	*p = *q;
	*q = t;
}
void av(int a, int b) //值传递 
{
	int t;
	t = a;
	a = b;
	b = t;
}

& represents a reference similar to * representing a pointer    

After running, you can learn that both the reference and pointer methods change the value. After the value is passed, the final output result is found to be that the values ​​​​of value1 and value2 have not changed.

Because in the av function, variables a and variable b copy the values ​​​​of value1 and value2 respectively and become new variables, swapping the values ​​​​of a and b does not change the values ​​​​of value1 and value2.

If you have any questions, please comment below and I will answer them for you.


Guess you like

Origin blog.csdn.net/samxiaoguai/article/details/80220197