Transferred from: http://myturn.blog.hexun.com/15584978_d.html
#include <iostream>
using namespace Std;
void Swap (int x, int y);
int main (void)
{
int a = 1;
int b = 2;
cout << "a =" << a << "," << "b =" << b << Endl;
Swap (A, b);
cout << "a =" << a << "," << "b =" << b << Endl;
System ("pause");
return 0;
}
One: Value passing
void Swap (int x, int y)
{
int temp = x;
x = y;
y = temp;
}
Output Result:
A = 1, b = 2
A = 1, b = 2
Cause: the Swap (int x, int y) function takes a value pass, and the actual arguments passed in are actually copies of a and b rather than themselves, so changes to the copy do not reflect A and B.
II: Reference Delivery
void Swap (int &x, int &y)
{
int temp = x;
x = y;
y = temp;
}
Output Result:
A = 1, b = 2
A = 2, B = 1
Cause: the Swap (int x, int y) function takes the form of a reference pass, and the actual arguments passed in are actually references to A and B, and the changes to the reference directly reflect A and B.
Three: pointer passing
1. Change the pointer itself
void Swap (int *x, int *y)
{
int *temp = x;
x = y;
y = temp;
}
Calling method: Swap (&a, &b);
Output Result:
A = 1, b = 2
A = 1, b = 2
Cause: the Swap (int x, int y) function takes a pointer pass, and the actual argument passed in is actually a copy of the pointer to A and B, and it changes the copy itself rather than its indirect reference, so it does not affect the value that the pointer points to, A and B.
2. Changing the pointer's indirect reference
void Swap (int *x, int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}
Calling method: Swap (&a, &b);
Output Result:
A = 1, b = 2
A = 2, B = 1
Cause: the Swap (int x, int y) function takes a pointer pass, although the incoming argument is also a copy of the pointer to a and B, but changes the indirect reference to the copy, either the pointer itself or its copy, pointing to the same value, so the change will reflect A and B.
Pass reference C (GO)