next up previous contents
Next: *可變參數 Up: 函式 Previous: call by value   Contents   DYWANG_HOME

call by reference

  1. call by reference:函式呼叫時傳入變數的位址,因此呼叫函式後,函式中若變更變數,結束函式後變數也跟著變動。
  2. 範例:輸入兩個數字,將其對換,呼叫時傳入變數的儲存位址 &a, &b (變數前加 & 符號),函式內取該位址上的值 *x, *y (變數前加 * 符號)。
    [dywang@dyw219 zzz]$ vim function3.c
    [dywang@dyw219 zzz]$ cat function3.c
    #include <stdio.h>
    
    void swap(int *x, int *y) {
    	int temp;
    
    	temp = *x;
    	*x = *y;
    	*y = temp;
    	return;
    }
     
    main() {
    	int a, b;
    
    	printf("Enter TWO integers: ");
    	scanf("%d %d", &a, &b);
    
    	printf("Before swap, a = %d, b = %d\n", a, b);
    	swap(&a, &b);
    	printf("After swap, a = %d, b = %d\n", a, b);
    }
    
  3. 編譯成功
    [dywang@dyw219 zzz]$ gcc -o function3 function3.c
    
  4. 執行結果:呼叫對換函式後,原變數 a b 的數值被調換了。
    [dywang@dyw219 zzz]$ ./function3
    Enter TWO integers: 10 20
    Before swap, a = 10, b = 20
    After swap, a = 20, b = 10
    [dywang@dyw219 zzz]$ ./function3
    Enter TWO integers: 21 11
    Before swap, a = 21, b = 11
    After swap, a = 11, b = 21
    



De-Yu Wang 2021-01-11