When implementing an infinite loop, is there a difference in using while(1) vs for(;;) vs goto (in C)?

前端 未结 8 1914
自闭症患者
自闭症患者 2020-12-02 23:06

When implementing an infinite loop, is there a difference in using while(1) vs for(;;) vs goto?

Thanks, Chenz

相关标签:
8条回答
  • 2020-12-02 23:14

    while(1) and for(;;) are exactly equivalent and both are well-understood idioms to code infinite loops.

    I would avoid the use of goto: to break from an infinite loop or to proceed to the next iteration, use break and continue.

    0 讨论(0)
  • 2020-12-02 23:15

    From what I recall of my "disassembling years", it won't make much a difference (compilers are smart enough). It is more about aesthetics IMO.

    0 讨论(0)
  • 2020-12-02 23:16

    In C, true is implemented as follows (depending on compiler)

    #define TRUE 1
    

    or

    #define TRUE (-1)
    

    AND false is implemented as

    #define FALSE 0
    

    so while (1) is equivalent to while (true) since 0 is considered false.

    the while (1) == for (; ;) as there are no stopping condition.

    which is translated to assembler as

    :loop
      ...
      ...
      ...
      goto loop
    

    so if the assembler code doesn't have a ret or exit instruction, it's considered a infinite loop.

    0 讨论(0)
  • 2020-12-02 23:27

    None. Use what is the most readable to you

    0 讨论(0)
  • 2020-12-02 23:28

    I just compared the unoptimized assembler output of gcc:

    # cat while.c 
    int main() {
        while(1) {};
        return 0;
    }
    
    # cat forloop.c 
    int main() {
        for (;;) { };
        return 0;
    }
    

    Make assembler output:

    # gcc -S while.c 
    # gcc -S forloop.c 
    

    Compare assembler files:

    # diff forloop.s while.s
    1c1
    <   .file   "forloop.c"
    ---
    >   .file   "while.c"
    

    As you can see there are no significant differences. Here is the output

    # cat while.s 
        .file   "while.c"
        .text
    .globl main
        .type   main, @function
    main:
        pushl   %ebp
        movl    %esp, %ebp
    .L2:
        jmp .L2                    # this is the loop in both cases
        .size   main, .-main
        .ident  "GCC: (GNU) 4.4.3"
        .section    .note.GNU-stack,"",@progbits
    

    While this is not a technical proof that they are the same, I'd say it is in 99.9% of the cases.

    0 讨论(0)
  • 2020-12-02 23:30

    There is hardly any difference in generated assembly. It's more of an stylistic issue:

    Goto - just ooogly: jumps backward, no explicit infinite block

    while(1) - better, requires "dummy" condition though and you'll be often warned by compiler(warning level 4) or static analysis tool

    for(;;) might not be the prettiest, but imho fits best because this construct cannot have any other meaning (compared to while). But some other people prefer while(1) for the "same" reason...

    0 讨论(0)
提交回复
热议问题