2)main函數在執行前和執行後有哪些操作

來源:互聯網
上載者:User

標籤:style   io   ar   color   使用   sp   on   div   bs   

main函數執行之前,主要就是初始化系統相關資源:? ? ?1. 設定棧指標? ? ?2. 初始化static靜態和global全域變數,即data段的內容? ? ?3. 將未初始化部分的全域變數賦初值:數值型short,int,long等為0,bool為FALSE,指標為NULL,等等,即.bss段的內容 ? ??? ? ?4. 全域對象初始化,在main之前調用建構函式? ? ?5. 將main函數的參數,argc,argv等傳遞給main函數,然後才真正運行main函數

main函數執行之後:? ? ?1. 全域對象的解構函式會在main函數之後執行;?? ? ?2. 可以用_onexit 註冊一個函數,它會在main 之後執行;?
如果你需要加入一段在main退出後執行的代碼,可以使用onexit()函數,註冊一個函數。??
? ? ? ? #include?<stdlib.h>
??????? #include?
<stdio.h>
????
????????
int?atexit(void?(*function")(void));
????????
void?fn1(?void?), fn2(?void?), fn3(?void?);
?????????????????????????
????????
int?main(?void?){
??????????? onexit( fn1 );
??????????? onexit( fn2 );
????????????
printf(?"This is executed first."?);
??????? }
????????
????????
void?fn1(){
????????????
printf(?" This is"?);
??????? }
????????
void?fn2(){
????????????
printf(?" executed next."?);
??????? }
結果:This is executed first.This is executed next.?
?

2)main函數在執行前和執行後有哪些操作

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.