next up previous contents
Next: call by value Up: 函式 Previous: 定義   Contents

宣告與呼叫

  1. 函式可以放在程式的任意位置,放在呼叫敍述之前,可以不用先宣告,但若放在呼叫敍述之後,則必須先宣告。宣告語法:
    return_type function_name( parameter list );
    
  2. 宣告範例
    int max(int num1, int num2);
    int max(int, int);
    
  3. 呼叫範例
    [dywang@dyw219 zzz]$ vim function1.c
    [dywang@dyw219 zzz]$ cat function1.c
    #include <stdio.h>
    
    int max(int num1, int num2) {
       int result;
    
       if (num1 > num2) result = num1;
       else result = num2;
       return result;
    }
    
    main() {
    	int a, b;
    
    	printf("Enter TWO integers: ");
    	scanf("%d %d", &a, &b);
    
    	printf("a = %d, b = %d, max = %d\n", a, b, max(a,b));
    }
    
  4. 編譯成功
    [dywang@dyw219 zzz]$ gcc -o function1 function1.c
    
  5. 執行結果
    [dywang@dyw219 zzz]$ ./function1
    Enter TWO integers: 10 20
    a = 10, b = 20, max = 20
    [dywang@dyw219 zzz]$ ./function1
    Enter TWO integers: 21 11
    a = 21, b = 11, max = 21
    



De-Yu Wang 2019-08-14