next up previous contents
Next: 運算子 Up: 變數與常數 Previous: 儲存類別   Contents

範圍原則

  1. Local 本地變數:變數宣告在函式或區塊中,程式離開函式或區塊後就失效。
    #include <stdio.h>
     
    int main ()
    {
      /* local variable declaration */
      int a, b;
      int c;
     
      /* actual initialization */
      a = 10;
      b = 20;
      c = a + b;
     
      printf ("value of a = %d, b = %d and c = %d\n", a, b, c);
     
      return 0;
    }
    
  2. Global 全域變數:宣告在函式外,通常在程式的最上方,變數保持其值直到程式結束,即使程式進入函式執行,依然可以存取這個變數。
    #include <stdio.h>
     
    /* global variable declaration */
    int g;
     
    int main ()
    {
      /* local variable declaration */
      int a, b;
     
      /* actual initialization */
      a = 10;
      b = 20;
      g = a + b;
     
      printf ("value of a = %d, b = %d and g = %d\n", a, b, g);
     
      return 0;
    }
    
  3. 程式中相同名子的本地變數及全域變數可以同時存在。
    #include <stdio.h>
     
    /* global variable declaration */
    int g = 20;
     
    int main ()
    {
      /* local variable declaration */
      int g = 10;
     
      printf ("value of g = %d\n",  g);
     
      return 0;
    }
    
  4. 範例
    #include <stdio.h>
     
    /* global variable declaration */
    int a = 20;
     
    int main ()
    {
      /* local variable declaration in main function */
      int a = 10;
      int b = 20;
      int c = 0;
    
      printf ("value of a in main() = %d\n",  a);
      c = sum( a, b);
      printf ("value of c in main() = %d\n",  c);
    
      return 0;
    }
    
    /* function to add two integers */
    int sum(int a, int b)
    {
        printf ("value of a in sum() = %d\n",  a);
        printf ("value of b in sum() = %d\n",  b);
    
        return a + b;
    }
    



2015-01-16