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

11,876

There is no difference once the program is compiled.

Here are some excerpts from three C programs and the corresponding generated assembly for all of them.

Let's try the for loop first:

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

Now we will try the while loop:

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

A terrible solution, the goto loop:

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

Now, if we examine the generated assemblies, using the command gcc -S loop.c, they all look like this (I didn't see any reason to post them separately, since they are identical):

   .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

This part is the loop. It declares a label, copies the address to the string into a register, calls a routine called puts, and jumps back to the label:

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

Since they all do exactly the same thing, clearly there is no technical advantage of any of them (at least if you are using gcc).

However, people have opinions, and may favor one over the others for whatever reason. Since for(;;) is only seven characters long, it is easier to type (this is my preference). On the other hand, while(1) gives the illusion of a test which always evaluates to true, which some may find more intuitive. Only a few crazy people like the goto solution best.

Edit: Apparently some compilers might produce a warning for while(1) because the condition is always true, but such warnings can be easily disabled and have no effect on the generated assembly.

Share:
11,876
Admin
Author by

Admin

Updated on June 08, 2022

Comments