Note: Here we set function A(a, b) as A and function B(c, d) as B to simplify.
Assume A call B, then the parameters of B are copied from A(i.e., any operation in B will not effected the variables in A).
void Swap(int x, int y)
{
int temp = a;
a = b;
b = temp;
}
Swap(value_A, value_B);
2. Call by address(pointer):
Transfer parameters by pointer. The main concept within this method is still the same as call by value; however, the "value" is a pointer, that's all.
void Swap(int* x, int* y)
{
int temp = *a;
*a = *b;
*b = temp;
}
Swap(&value_A, &value_B);
3. Call by reference:
Only support for C++ and the basic idea is aliases for each parameter.
void Swap(int & x, int & y)
{
int temp = a;
a = b;
b = temp;
}
Swap(value_A, value_B);
The pointer may be copied to caller function when we use "Call by pointer" to transfer parameters. However, if we want to change the value of pointer(i.e., isn't the variable directed to pointer) and generate a non-locally influence "Call by pointer" is not suitable enough. Hence, we have to use "Pointer to pointer" or "Reference to pointer".
Note: Pointer to pointer vs. Reference to pointer(i.e., int** vs. int*&)
Here we show a example to illustrate our concept:
int gInt = 0;
void ChangePointer(int* pInt)
{
pInt = &gInt;
}
void main()
{
int lInt = 1;
int* lPtr = &lInt;
ChangePtr(lPtr);
printf("%d\n", *lPtr);
}
In this case, the parameter *pInt is copied by lPtr in main(). (reference "2. Call by pointer")
4. Pointer to pointer:
int gInt = 0;
void ChangePointer(int** pInt)
{
*pInt = &gInt;
}
void main()
{
int lInt = 1;
int* lPtr = &lInt;
ChangePtr(&lPtr);
printf("%d\n", *lPtr);
}
In this case, result will print 0(i.e., value of gInt).
5. Reference to pointer:
int gInt = 0;
void ChangePointer(int* &pInt)
{
pInt = &gInt;
}
void main()
{
int lInt = 1;
int* lPtr = &lInt;
ChangePtr(lPtr);
printf("%d\n", *lPtr);
}
In this case, we will get the same result as "4. Pointer to pointer". Function declaration (int* &pInt) is the same as "reference pointer to pointer". Hence, lPtr in main() and pInt in ChangePointer() are identical.
No comments:
Post a Comment