W3Cschool
恭喜您成為首批注冊用戶
獲得88經驗值獎勵
靜態(tài)變量可以保留從一個函數調用到的信息下一個。
您可以使用此聲明聲明一個靜態(tài)變量 count
:
static int count = 0;
單詞static是一個關鍵字。
單詞static是一個關鍵字。...
被聲明為靜態(tài)的變量的初始化只發(fā)生一次,就在開頭程序。
雖然靜態(tài)變量僅在包含其聲明的函數內可見,它本質上是一個全局變量。
以下代碼顯示了靜態(tài)變量和自動變量之間的差異。
#include <stdio.h>
// Function prototypes
void test1(void);
void test2(void);
int main(void) {
for(int i = 0 ; i < 5 ; ++i) {
test1();
test2();
}
return 0;
}
// Function test1 with an automatic variable
void test1(void)
{
int count = 0;
printf("test1 count = %d\n", ++count );
}
// Function test2 with a static variable
void test2(void)
{
static int count = 0;
printf("test2 count = %d\n", ++count );
}
上面的代碼生成以下結果。
為了在函數之間共享變量,在程序文件的開頭聲明一個變量所以他們“超出了功能的范圍。
這些被稱為全局變量,因為它們“可以隨時隨地訪問。
#include <stdio.h>
//w w w. jav a 2 s . c o m
int count = 0; // Declare a global variable
// Function prototypes
void test1(void);
void test2(void);
int main(void) {
int count = 0; // This hides the global count
for( ; count < 5 ; ++count) {
test1();
test2();
}
return 0;
}
void test1(void) {
printf("test1 count = %d\n", ++count);
}
void test2(void) {
printf("test2 count = %d\n", ++count);
}
上面的代碼生成以下結果。
一個函數可以調用自身。這稱為遞歸。
調用自身的函數也必須包含停止過程的方式。
以下代碼顯示如何計算整數的階乘。
任何整數的階乘是所有從1到的整數的乘積整數本身。
#include <stdio.h>
/* w w w. j a v a2 s. c om*/
unsigned long long factorial(unsigned long long);
int main(void) {
unsigned long long number = 10LL;
printf("The factorial of %llu is %llu\n", number, factorial(number));
return 0;
}
// A recursive factorial function
unsigned long long factorial(unsigned long long n) {
if(n < 2LL)
return n;
return n*factorial(n - 1LL);
}
上面的代碼生成以下結果。
調用abort()函數會導致程序異常終止。
它不需要參數。
當你想結束一個程序時,這樣調用:
abort(); // Abnormal program end
exit()函數導致程序的正常終止。
該函數需要一個類型的參數int表示終止時的程序狀態(tài)。
參數可以為0或EXIT_SUCCESS以指示a成功終止,并將其返回到主機環(huán)境。
例如:
exit(EXIT_SUCCESS); // Normal program end
如果參數是EXIT_FAILURE,則將向主機環(huán)境返回故障終止的指示。
您可以通過調用atexit()注冊您自己的函數,由exit()調用。
您調用atexit()函數來標識要執(zhí)行的函數當應用程序終止時。
這里的你怎么可能這樣做:
void CleanUp(void);// Prototype of function if(atexit(CleanUp)) printf("Registration of function failed!\n");
_Exit()函數與exit()基本上執(zhí)行相同的工作。
_Exit()不會調用任何注冊的函數。
你調用_Exit()像這樣:
_Exit(1); // Exit with status code 1
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯系方式:
更多建議: