2014
Mar
24

不管是工作上或是在家裡寫程式,我都需要同時開發 Javascript, PHP, C&C++ 這幾種程式,雖然都是寫了好幾年的程式,但還是常常會搞混,今天就將這幾個語言的 「Call by reference 」用法記錄下來。

C&C++ Call by Reference

C 語言的 call by reference 是有很標準的定義,int a 代表一般的變數,而 int &a 代表變數會以 call by reference 的方式傳遞,這時 a 與傳入值(b)會同步,看下面的範例,在 function test1 中,不管 a 值如何變化,傳入的值都不會受影響,而在 function test2 中,則是使用 call by reference 的方式,所以當 a 被改變了, 傳入的值 b 也跟著變化 。

Example
  1. #include "stdio.h"
  2. #include "stdlib.h"
  3. void test1(int a) {
  4. a = 10;
  5. }
  6. void test2(int &a) {
  7. a = 10;
  8. }
  9. main() {
  10. int a = 1;
  11. int b = 1;
  12. int c[2] = {1, 0};
  13. test1(a);
  14. printf("%i n", a);
  15. //output: 1
  16. test2(b);
  17. printf("%i n", b);
  18. //output: 10
  19. }

C&C++ 中的 Array 一定會是一個指標物件,所以強迫變成 call by reference 的方式。

Example
  1. #include "stdio.h"
  2. #include "stdlib.h"
  3. void test3(int array[]) {
  4. array[1] = 2;
  5. }
  6. main() {
  7. int c[2] = {1, 0};
  8. test3(c);
  9. printf("%i %i", c[0], c[1]);
  10. // output: 1 2
  11. }

PHP Call by Reference

PHP 要將變數以 Reference 得方式傳給 function 時,必須在 function 定義變數名稱時,前面加上 「&」 符號 ,下面的兩個 function,第一個 test1 不帶 「&」 符號,所以沒有 Reference 的效果,就算你的變數是 Array 也是一樣無效,而第二個 test2 則有 Reference 的效果,當變數值被改變,原傳入前的變數也跟著同步。

Example
  1. <?php
  2. $a = array("ss");
  3. $b = array("ss");
  4. function test1($array) {
  5. $array[] = "bbb";
  6. }
  7. function test2(&$array) {
  8. $array[] = "bbb";
  9. }
  10. test1($a);
  11. print_r($a);
  12. // Output: Array (ss)
  13. test2($b);
  14. print_r($b);
  15. //Output: Array(ss, bbb)

Javascript call by reference

Javascript 中,只要是 Array, Object 都會以 call by reference 的方式傳遞,而一般的 String, Number 等變數值則以 call by value 的方式傳遞,看下面的範例, test1 的參數 i 是一值的數字,所以沒有 call by reference 的效果,而 test2 的參數 array ,他的變數形態就是一個 Array,所以只要 array 被修改,傳入的參數值也會跟著變動。

Example
  1. function test1(i) {
  2. i = 2;
  3. }
  4. function test2(array) {
  5. array[1] = 2;
  6. }
  7. var a = 1;
  8. var b = [1];
  9. test1(a);
  10. console.log(a);
  11. //output: 1
  12. test2(b);
  13. console.log(b);
  14. //output: 1, 2

回應 (Leave a comment)