while(1) 和 for(;;)有什么區(qū)別?
點(diǎn)擊上方“程序員大白”,選擇“星標(biāo)”公眾號
重磅干貨,第一時(shí)間送達(dá)
作者 |?strongerHuang 微信公眾號 |?嵌入式專
要回答這個(gè)問題,其實(shí)你各自編寫一段while(1) 和 for(;;)的代碼,編譯對比一下代碼大小和匯編文件,你就大概知道了。
while(1)和for(;;)語法表達(dá)
while( 表達(dá)式 ){語句}
其中:
表達(dá)式:是循環(huán)條件
語句:為循環(huán)體。

for(表達(dá)式1; 表達(dá)式2; 表達(dá)式3){語句}
1.先求解表達(dá)式1
2.求解表達(dá)式2
若其值為真(非0),則執(zhí)行for語句中指定的內(nèi)嵌語句,然后執(zhí)行下面第3)步;
若其值為假(0),則結(jié)束循環(huán),轉(zhuǎn)到第5)步。
3.求解表達(dá)式3
4.轉(zhuǎn)回上面第2)步繼續(xù)執(zhí)行。
5.循環(huán)結(jié)束,執(zhí)行for語句下面的一個(gè)語句。

while(1)和for(;;)異同點(diǎn)
驗(yàn)證while(1)和for(;;)差異
// filename: while.cint main(int argc, char const *argv[]){while(1){}return 0;}
// filename: for.cint main(int argc, char const *argv[]){for(;;){}return 0;}
gcc -S -o while.s while.cgcc -S -o for.s for.c
; filename: whiles.file "while.c".text.globl main.type main, @functionmain:.LFB0:.cfi_startprocpushq %rbp.cfi_def_cfa_offset 16.cfi_offset 6, -16movq %rsp, %rbp.cfi_def_cfa_register 6movl %edi, -4(%rbp)movq %rsi, -16(%rbp).L2:jmp .L2.cfi_endproc.LFE0:.size main, .-main.ident "GCC: (GNU) 9.3.0".section .note.GNU-stack,"",@progbits
; filename: for.s.file "for.c".text.globl main.type main, @functionmain:.LFB0:.cfi_startprocpushq %rbp.cfi_def_cfa_offset 16.cfi_offset 6, -16movq %rsp, %rbp.cfi_def_cfa_register 6movl %edi, -4(%rbp)movq %rsi, -16(%rbp).L2:jmp .L2.cfi_endproc.LFE0:.size main, .-main.ident "GCC: (GNU) 9.3.0".section .note.GNU-stack,"",@progbits
推薦閱讀
關(guān)于程序員大白
程序員大白是一群哈工大,東北大學(xué),西湖大學(xué)和上海交通大學(xué)的碩士博士運(yùn)營維護(hù)的號,大家樂于分享高質(zhì)量文章,喜歡總結(jié)知識,歡迎關(guān)注[程序員大白],大家一起學(xué)習(xí)進(jìn)步!
評論
圖片
表情


