while(true) / while(1) vs. for(;;)



可能重复:
for(;;(还是while(true(-哪个是正确的C#无限循环
为什么选择for(;;({}而不是while(1(?

while(true)while(1)for(;;)之间有什么区别?在C#和C/C++等语言中,它们都是无限循环。但是一个比另一个好吗?有什么想法吗?

编译程序后没有任何区别。

以下是三个C程序的一些摘录,以及为所有这些程序生成的相应程序集。

让我们先试试for循环:

#include <stdio.h>
int main(){
   for(;;)
      printf("This is a loopn");
   return 0;
}

现在我们将尝试while循环:

#include <stdio.h>
int main(){
   while(1)
      printf("This is a loopn");
   return 0;
}

一个糟糕的解决方案,goto循环:

#include <stdio.h>
int main(){
   alpha:
      printf("This is a loopn");
      goto alpha;
   return 0;
}

现在,如果我们使用命令gcc -S loop.c检查生成的程序集,它们看起来都是这样的(我看不出有任何理由单独发布它们,因为它们是相同的(:

   .file "loop.c"
   .section .rodata
.LC0:
   .string  "This is a loop"
   .text
.globl main
   .type main, @function
main:
   leal  4(%esp), %ecx
   andl  $-16, %esp
   pushl -4(%ecx)
   pushl %ebp
   movl  %esp, %ebp
   pushl %ecx
   subl  $4, %esp
.L2:
   movl  $.LC0, (%esp)
   call  puts
   jmp   .L2
   .size main, .-main
   .ident   "GCC: (GNU) 4.2.4 (Ubuntu 4.2.4-1ubuntu4)"
   .section .note.GNU-stack,"",@progbits

这部分是循环。它声明一个标签,将地址复制到字符串的寄存器中,调用一个名为puts的例程,然后跳回标签:

.L2:
   movl  $.LC0, (%esp)
   call  puts
   jmp   .L2

由于它们都做着完全相同的事情,显然它们中的任何一个都没有技术优势(至少如果您使用的是gcc(。

然而,人们有自己的观点,并且可能出于任何原因而偏袒一个人。由于for(;;)只有七个字符长,所以打字更容易(这是我的偏好(。另一方面,while(1)给人一种总是评估为true的测试的错觉,有些人可能会觉得这更直观。只有少数疯子最喜欢goto解决方案。

编辑:显然,某些编译器可能会为while(1)生成警告,因为条件始终为true,但这样的警告很容易被禁用,对生成的程序集没有影响。

最新更新