C作用域規則
局部變量
在某個函數或塊的內部聲明的變量稱爲局部變量。它們只能被該函數或該代碼塊內部的語句使用
#include <stdio.h>
int main ()
{
/* 局部變量聲明 */
int a, b;
int c;
/* 實際初始化 */
a = 10;
b = 20;
c = a + b;
printf ("a = %d, b = %d and c = %d\n", a, b, c);
return 0;
}
全局變量
全局變量是定義在函數外部,可以被任何函數訪問。也就是說,全局變量在聲明後整個程序中都是可用的。
#include <stdio.h>
/* 全局變量聲明 */
int g;
int main ()
{
/* 局部變量聲明 */
int a, b;
/* 實際初始化 */
a = 10;
b = 20;
g = a + b;
printf ("a = %d, b = %d and g = %d\n", a, b, g);
return 0;
}
形式參數
函數的參數,形式參數,被當作該函數內的局部變量,它們會優先覆蓋全局變量。
#include <stdio.h>
int add(int, int)
int main ()
{
/* 局部變量聲明 */
int a, b;
int total;
/* 實際初始化 */
a = 10;
b = 20;
total = add(a, b);
printf ("a = %d, b = %d and total = %d\n", a, b, total);
return 0;
}
int add(int a, int b){
printf("a = %d\n", a);
printf("b = %d\n", b);
return a + b;
}