我用K讀取的C編程語言的第2章& R:「類型,運算符&表達式」,第2.4節,其中,在我發現而作出的以下語句:聲明:K&R
如果變量不是自動的,初始化爲 只做一次,概念上在程序開始執行之前完成,並且 初始化程序必須是一個常量表達式。一個明確的 初始化的自動變量被初始化,每次函數 或者阻塞它在進入;初始化器可以是任何表達式。
以上各行不太清楚它們是什麼意思?
我用K讀取的C編程語言的第2章& R:「類型,運算符&表達式」,第2.4節,其中,在我發現而作出的以下語句:聲明:K&R
如果變量不是自動的,初始化爲 只做一次,概念上在程序開始執行之前完成,並且 初始化程序必須是一個常量表達式。一個明確的 初始化的自動變量被初始化,每次函數 或者阻塞它在進入;初始化器可以是任何表達式。
以上各行不太清楚它們是什麼意思?
安自動變量是一個正常變量。這些變量在堆棧上創建並在每次通過時進行初始化。例如:
int example_auto(){
int foo = 0;
foo++;
return foo;
}
foo
是每次調用example_auto()
時間初始化爲0
。函數始終返回1.
A 靜態變量是一個聲明爲static
的變量,或作爲全局變量(任何函數外部)聲明的變量。與自動變量不同,這些變量在程序啓動時(或接近)初始化一次。例如:
int example_static(){
static int foo = 0;
foo++;
return foo;
}
foo
被初始化一次。 example_static()
返回1的第一次調用它,然後如圖2所示,然後3等
int a = 5;
int b = a; //error, a is not a constant expression
int main(void)
{
static int c = a; //error, a is not a constant expression
int d = a; //okay, a don't have to be a constant expression
return 0;
}
僅d
是一個自動可變的,並且因此僅d
被允許獲得與其他變量初始化。
在C塊中,您可以定義兩種局部變量:靜態和自動。請注意,本地只意味着該變量僅在函數內部可見。
然後每次調用函數/塊時重新創建一個自動變量,並在控件離開函數/塊時被銷燬。每次創建時都會進行初始化。
靜態局部變量在程序的整個生命週期中只創建一次。它被破壞並且程序結束。它在創建的同時被初始化:在程序開始時只有一次(概念上它可能略有不同)。每次
一個明確的初始化自動變量初始化函數或阻止它在輸入:
除了其他的答案,自動,正如其名稱所暗示的,也有做在運行時處理變量的方式。即它在其定義的邏輯塊內的生命將被創建,並在進入和離開時自動銷燬。 Memory is allocated and deallocated automatically within the variable's context。無需顯式創建或銷燬內存,因爲每次輸入並退出邏輯塊(由{...}
定義)時都會執行此操作。因此術語自動。
初始值設定項可以是任何表達式。
自動自動變量可以使用其他先前初始化的變量,常量或表達式進行初始化。
#define MAX 20.0
float d;
int func(void)
{
int a = 10; //automatic
int b = a + 3; //automatic
float c = MAX; //automatic
d = MAX; //d is a file global, not automatic,
//memory created outside of local scope,
//memory is not de-allocated when function exits
static int e = 0; //Not automatic as static gives local variables life
//beyond the function, i.e. outside scope of {...}
//memory, and value of e remain when function exits
//and between calls
return 0;
}
這指出一個局部變量也被稱爲自動變量可以由一個恆定或非恆定表達被初始化 -
int a = 5;
int main()
{
int c = a; // local or automatic variable initialized by a non
constant variable
}
但是外部也被稱爲一個全局變量和靜態變量不能由非常量變量初始化。
int a = 3
int b = a // cannot be initialized by non constant variable
int main()
{
static int d;
d = a // cannot be initialized by a non constant variable
}
它還指出,自動或局部變量各自它們在代碼塊是由編譯器運行時間重新intialized。因爲變量的內存位置每次進入代碼塊時都會被編譯器自動分配和釋放。
void abc(void);// function parameter
int main()
{
abc();
abc();
}
void abc()
{
int i = 0;// automatic variable i is re-intialized every time abc is called
static x = 0; //static variable retains its value
i ++ ;
x ++;
printf("%d\n",i);
printf("%d\n",x);
}
輸出 - 1 1 1 2