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

Possible duplicate:
for (;;) or while (true) - what is the correct C # infinite loop?
Why choose (;;) {} while (1)?

What is the difference between while(true) , while(1) and for(;;) ? All of them are infinite loops in languages โ€‹โ€‹like C # and C / C ++. But is one better than the other? Any ideas?

+4
source share
1 answer

There is no difference after compiling the program.

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

First try a for loop:

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

Now we try the while :

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

Awful solution, goto loop:

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

Now, if we look at the generated assemblies using the gcc -S loop.c , they all look like this (I did not see any reason to place 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 a loop. It declares a label, copies the address into a string in a register, calls a procedure called puts and returns to the label:

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

Since they all do exactly the same thing, itโ€™s clear that none of them have a technical advantage (at least if you use gcc ).

However, people have their own opinions, and for some reason they can speak out for others. 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 that always evaluates to true , which some may find more intuitive. Only a few crazy people such as the goto solution are the best.

Edit: Apparently, some compilers may issue a warning for while(1) , because the condition is always true, but such warnings can be easily turned off and do not affect the generated assembly.

+10
source

All Articles