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