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

前端 未结 8 1975
自闭症患者
自闭症患者 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: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.

提交回复
热议问题