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

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

    Although there's no significant difference as mentioned in the other posts, a common reason to use for (;;) instead of while (1) is that static analysis tools (and some compilers with certain warning levels) often complain about the while loop.

    Goto is a bit nasty, but should produce the same code as the others. Personally, I stick to for (;;) (to keep Lint happy), but I have no problem with while (1).

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

    They are equivalent, even if you turn the optimizer off.

    Example:

    #include <stdio.h>
    
    extern void f(void) {
        while(1) {
            putchar(' ');
        }
    }
    
    extern void g(void) {
        for(;;){
            putchar(' ');
        }
    }
    
    extern void h(void) {
        z:
            putchar(' ');
        goto z;
    }
    

    Compile with gcc -O0 gives equivalent assembly for all 3 functions:

     f:
     ;  [ EXTERNAL ]
     ;
     +00000 00000fb4 80402DE9             stmdb             sp!,{r7,lr}
     +00004 00000fb8 00708DE2             add               r7,sp,#0x0
     +00008 00000fbc 2000A0E3 loc_000008: mov               r0,#0x20
     +0000c 00000fc0 0A0000EB             bl                putchar (stub)
     +00010 00000fc4 FCFFFFEA             b                 loc_000008
     ;
     ;
     g:
     ;  [ EXTERNAL ]
     ;
     +00000 00000fc8 80402DE9             stmdb             sp!,{r7,lr}
     +00004 00000fcc 00708DE2             add               r7,sp,#0x0
     +00008 00000fd0 2000A0E3 loc_000008: mov               r0,#0x20
     +0000c 00000fd4 050000EB             bl                putchar (stub)
     +00010 00000fd8 FCFFFFEA             b                 loc_000008
     ;
     ;
     h:
     ;  [ EXTERNAL ]
     ;
     +00000 00000fdc 80402DE9             stmdb             sp!,{r7,lr}
     +00004 00000fe0 00708DE2             add               r7,sp,#0x0
     +00008 00000fe4 2000A0E3 loc_000008: mov               r0,#0x20
     +0000c 00000fe8 000000EB             bl                putchar (stub)
     +00010 00000fec FCFFFFEA             b                 loc_000008
    
    0 讨论(0)
提交回复
热议问题