你会用while(1)还是for(;;)写循环代码?

嵌入式Linux

共 2197字,需浏览 5分钟

 · 2021-01-21

看代码看到for(;;),然后觉得为什么不写成while(1)呢,所以就做了下面的测试。

网上有解释,因为while需要做一次判断,理论上执行会花费的时间更久,for(;;)只是执行了两次空语句,执行会更快

for.c

#include 
int main(){
   for(;;)
      printf("This is a loop\n");
   return 0;
}

while.c

#include 
int main(){
   while(1)
      printf("This is a loop\n");
   return 0;
}

goto.c

#include 
int main(){
   start:
      printf("This is a loop\n");
    goto start;
   return 0;
}

用gcc -S xxx.c 执行后得到三个文件

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.047.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.

在上面测试结束后,我还特意打开了我的keil软件,结果发现两个生成的机器码都是一样的。

所以说,如果在项目中遇到这样的写法,就不要再感觉奇怪了,他们都是没啥问题的。

只不过for(;;)看起来更优雅一些。

还有一种情况while(1)里面的1是一个常量,在一些编译器中,设置的检查规则比较高的话,会提示一个警告,for(;;)就不会存在这种问题,因为里面就没有变量,也没有常量。



推荐阅读:
专辑|Linux文章汇总
专辑|程序人生
专辑|C语言
我的知识小密圈



浏览 12
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报