next up previous contents
Next: call by reference Up: 函式 Previous: 宣告與呼叫   Contents   DYWANG_HOME

call by value

  1. call by value:函式呼叫時傳入參數值,呼叫時複製一份給函式,不會影響目前的變數值。
  2. 範例:輸入兩個數字,將其對換,呼叫時傳入變數的值。
    [dywang@dyw219 zzz]$ cat function2.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 function2 function2.c
    
  4. 執行結果:不論對換前後,原變數 a b 的數值皆不變。
    [dywang@dyw219 zzz]$ ./function2
    Enter TWO integers: 10 20
    Before swap, a = 10, b = 20
    After swap, a = 10, b = 20
    



De-Yu Wang 2021-01-11