你会用while(1)还是for(;;)写循环代码?
生活随笔
收集整理的這篇文章主要介紹了
你会用while(1)还是for(;;)写循环代码?
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
看代碼看到for(;;),然后覺得為什么不寫成while(1)呢,所以就做了下面的測試。
網(wǎng)上有解釋,因為while需要做一次判斷,理論上執(zhí)行會花費的時間更久,for(;;)只是執(zhí)行了兩次空語句,執(zhí)行會更快
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í)行后得到三個文件
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.在上面測試結(jié)束后,我還特意打開了我的keil軟件,結(jié)果發(fā)現(xiàn)兩個生成的機器碼都是一樣的。
所以說,如果在項目中遇到這樣的寫法,就不要再感覺奇怪了,他們都是沒啥問題的。
只不過for(;;)看起來更優(yōu)雅一些。
還有一種情況while(1)里面的1是一個常量,在一些編譯器中,設置的檢查規(guī)則比較高的話,會提示一個警告,for(;;)就不會存在這種問題,因為里面就沒有變量,也沒有常量。
推薦閱讀:
專輯|Linux文章匯總
專輯|程序人生
專輯|C語言
我的知識小密圈
總結(jié)
以上是生活随笔為你收集整理的你会用while(1)还是for(;;)写循环代码?的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 麒麟操作系统激活相关问题
- 下一篇: 《算法》第四版入门准备