你会用while(1)还是for(;;)写循环代码?
看代碼看到for(;;),然后覺(jué)得為什么不寫(xiě)成while(1)呢,所以就做了下面的測(cè)試。
網(wǎng)上有解釋,因?yàn)閣hile需要做一次判斷,理論上執(zhí)行會(huì)花費(fèi)的時(shí)間更久,for(;;)只是執(zhí)行了兩次空語(yǔ)句,執(zhí)行會(huì)更快
for.c
#include?<stdio.h> int?main(){for(;;)printf("This?is?a?loop\n");return?0; }while.c
#include?<stdio.h> int?main(){while(1)printf("This?is?a?loop\n");return?0; }goto.c
#include?<stdio.h> int?main(){start:printf("This?is?a?loop\n");goto?start;return?0; }用gcc -S xxx.c 執(zhí)行后得到三個(gè)文件
for.s
?.file?"for.c".text.p?.rodata .LC0:.string?"This?is?a?loop".text.globl?main.type?main,?@function main: .LFB0:.cfi_startprocpushq?%rbp.cfi_def_cfa_offset?16.cfi_offset?6,?-16movq?%rsp,?%rbp.cfi_def_cfa_register?6 .L2:leaq?.LC0(%rip),?%rdicall?puts@PLTjmp?.L2.cfi_endproc .LFE0:.size?main,?.-main.ident?"GCC:?(Ubuntu?7.5.0-3ubuntu1~18.04)?7.5.0".p?.note.GNU-stack,"",@progbitswhile.s
?.file?"while.c".text.p?.rodata .LC0:.string?"This?is?a?loop".text.globl?main.type?main,?@function main: .LFB0:.cfi_startprocpushq?%rbp.cfi_def_cfa_offset?16.cfi_offset?6,?-16movq?%rsp,?%rbp.cfi_def_cfa_register?6 .L2:leaq?.LC0(%rip),?%rdicall?puts@PLTjmp?.L2.cfi_endproc .LFE0:.size?main,?.-main.ident?"GCC:?(Ubuntu?7.5.0-3ubuntu1~18.04)?7.5.0".p?.note.GNU-stack,"",@progbitsgoto.s
?.file?"goto.c".text.p?.rodata .LC0:.string?"This?is?a?loop".text.globl?main.type?main,?@function main: .LFB0:.cfi_startprocpushq?%rbp.cfi_def_cfa_offset?16.cfi_offset?6,?-16movq?%rsp,?%rbp.cfi_def_cfa_register?6 .L2:leaq?.LC0(%rip),?%rdicall?puts@PLTjmp?.L2.cfi_endproc .LFE0:.size?main,?.-main.ident?"GCC:?(Ubuntu?7.5.0-3ubuntu1~18.04)?7.5.0".p?.note.GNU-stack,"",@progbitsgcc 版本
gcc?(Ubuntu?7.5.0-3ubuntu1~18.04)?7.5.0 Copyright?(C)?2017?Free?Software?Foundation,?Inc. This?is?free?software;?see?the?source?for?copying?conditions.??There?is?NO warranty;?not?even?for?MERCHANTABILITY?or?FITNESS?FOR?A?PARTICULAR?PURPOSE.在上面測(cè)試結(jié)束后,我還特意打開(kāi)了我的keil軟件,結(jié)果發(fā)現(xiàn)兩個(gè)生成的機(jī)器碼都是一樣的。
所以說(shuō),如果在項(xiàng)目中遇到這樣的寫(xiě)法,就不要再感覺(jué)奇怪了,他們都是沒(méi)啥問(wèn)題的。
只不過(guò)for(;;)看起來(lái)更優(yōu)雅一些。
還有一種情況while(1)里面的1是一個(gè)常量,在一些編譯器中,設(shè)置的檢查規(guī)則比較高的話,會(huì)提示一個(gè)警告,for(;;)就不會(huì)存在這種問(wèn)題,因?yàn)槔锩婢蜎](méi)有變量,也沒(méi)有常量。
推薦閱讀:
專(zhuān)輯|Linux文章匯總
專(zhuān)輯|程序人生
專(zhuān)輯|C語(yǔ)言
我的知識(shí)小密圈
總結(jié)
以上是生活随笔為你收集整理的你会用while(1)还是for(;;)写循环代码?的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
                            
                        - 上一篇: 麒麟操作系统激活相关问题
 - 下一篇: 《算法》第四版入门准备