August 2, 2013

C/C++ call by value, call by address(pointer), and call by reference

Note: Here we set function A(a, b) as A and function B(c, d) as B to simplify.

1. Call by value:
     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

三個逗號俱樂部

《免責聲明》 本部落格不針對任何金融商品進行買賣建議, 內容來自公開資訊觀測站之分享與各大媒體之評論為主, 投資人應審慎評估並獨立判斷,切勿以本部落格資訊作為投資依據。 靜候 時機來臨;瞬間掌握重壓;享受 獲利奔馳。 -------------------------...