If we wants to make a parameter-passing, there are usually three ways to go, namely common parameters, pointer parameters and quoting parameters.
- Common parameters
The parameters passed into the function in this form is formal parameters, which means is doesn’t change the original value outside the function. The sample code is as follows.
#include <bits/stdc++.h>
using namespace std;
void swap(int a, int b)
{
int c = a;
a = b;
b = c;
}
int main()
{
int a = 1, b = 2;
cout << "before: a = " << a << ", b = " << b << endl;
swap(a, b);
cout << "after: a = " << a << ", b = " << b << endl;
return 0;
}
The output is as follows.
before: a = 1, b = 2
after: a = 1, b = 2
- Pointer parameters
The parameters passed into the function in this form is pointer parameters, which can be simply understood as two addresses. Therefore, the oprations done in the function are all based in the address, which will surely change the original value outside the function.
#include <bits/stdc++.h>
using namespace std;
void swap(int *a, int *b)
{
int c = *a;
*a = *b;
*b = c;
}
int main()
{
int a = 1, b = 2;
cout << "before: a = " << a << ", b = " << b << endl;
swap(&a, &b);
cout << "after: a = " << a << ", b = " << b << endl;
return 0;
}
The output is as follows.
before: a = 1, b = 2
after: a = 2, b = 1
- quoting parameters
It’s already widely known that quoting is equivalent to aliasing, so that the ‘a, b’ in the function have the same adresses with the ‘a, b’ outside. Therefore, it will definitely change the original value outside.The sample code is as follows.
#include <bits/stdc++.h>
using namespace std;
void swap(int &a, int &b)
{
int c = a;
a = b;
b = c;
}
int main()
{
int a = 1, b = 2;
cout << "before: a = " << a << ", b = " << b << endl;
swap(a, b);
cout << "after: a = " << a << ", b = " << b << endl;
return 0;
}
The output is as follows.
before: a = 1, b = 2
after: a = 2, b = 1
- What’s more, I’d like to provide some interesting samples for address. This is my TODO-work.
- Quoting will not define a new variable, and the system won’t open up new memory space. That is, ‘a’ and ‘b’ point to the same address.
- Quoting is often used to pass parameters into a function. Operations for the quoting inside the function are equivalent to operating the original values outside.