Search code examples
coptimizationloopsinfinite

Best infinite loop


Possible Duplicate:
while (1) Vs. for (;;) Is there a speed difference?

Hi,

Which is better,faster and more optimized way to implement infinite loop - for(;;) or while(1)? and why?


Solution

  • In any normal compiler, there should be absolutely no difference. For example, here's what LLVM-clang generates (with the -O3 flag) for while (1) {}:

        .file   "test.c"
        .text
        .globl  main
        .align  16, 0x90
        .type   main,@function
    main:
        pushl   %ebp
        movl    %esp, %ebp
        .align  16, 0x90
    .LBB0_1:
        jmp .LBB0_1
    

    Note the jmp .LBB0_1 part, which is the actual infinite loop. For the for (;;) kind, it generates absolutely the same code.

    You can also try with other compilers for fun, but it's best just stop worrying about it.


    OK, I just had to try with gcc as well:

        .file   "test.c"
        .text
    .globl main
        .type   main, @function
    main:
        pushl   %ebp
        movl    %esp, %ebp
    .L2:
        jmp .L2