你會用while(1)還是for(;;)寫循環(huá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
- .section .rodata
- .LC0:
- .string "This is a loop"
- .text
- .globl main
- .type main, @function
- main:
- .LFB0:
- .cfi_startproc
- pushq %rbp
- .cfi_def_cfa_offset 16
- .cfi_offset 6, -16
- movq %rsp, %rbp
- .cfi_def_cfa_register 6
- .L2:
- leaq .LC0(%rip), %rdi
- call puts@PLT
- jmp .L2
- .cfi_endproc
- .LFE0:
- .size main, .-main
- .ident "GCC: (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0"
- .section .note.GNU-stack,"",@progbits
while.s
- .file "while.c"
- .text
- .section .rodata
- .LC0:
- .string "This is a loop"
- .text
- .globl main
- .type main, @function
- main:
- .LFB0:
- .cfi_startproc
- pushq %rbp
- .cfi_def_cfa_offset 16
- .cfi_offset 6, -16
- movq %rsp, %rbp
- .cfi_def_cfa_register 6
- .L2:
- leaq .LC0(%rip), %rdi
- call puts@PLT
- jmp .L2
- .cfi_endproc
- .LFE0:
- .size main, .-main
- .ident "GCC: (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0"
- .section .note.GNU-stack,"",@progbits
goto.s
- .file "goto.c"
- .text
- .section .rodata
- .LC0:
- .string "This is a loop"
- .text
- .globl main
- .type main, @function
- main:
- .LFB0:
- .cfi_startproc
- pushq %rbp
- .cfi_def_cfa_offset 16
- .cfi_offset 6, -16
- movq %rsp, %rbp
- .cfi_def_cfa_register 6
- .L2:
- leaq .LC0(%rip), %rdi
- call puts@PLT
- jmp .L2
- .cfi_endproc
- .LFE0:
- .size main, .-main
- .ident "GCC: (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0"
- .section .note.GNU-stack,"",@progbits
gcc 版本
- 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是一個常量,在一些編譯器中,設(shè)置的檢查規(guī)則比較高的話,會提示一個警告,for(;;)就不會存在這種問題,因為里面就沒有變量,也沒有常量。