What kind of loop is for (;;)?

后端 未结 12 1016
暖寄归人
暖寄归人 2021-01-04 04:42

Found in torvalds/linux-2.6.git -> kernel/mutex.c line 171

I have tried to find it on Google and such to no avail.

What does for (;;) instruct?<

12条回答
  •  时光取名叫无心
    2021-01-04 05:02

    It is functionally equivilent to while(true) { }.

    The reason why the for(;;) syntax is sometimes preferred comes from an older age where for(;;) actually compiled to a slightly faster machine code than while(TRUE) {}. This is because for(;;) { foo(); } will translate in the first pass of the compiler to:

    lbl_while_condition:
       mov $t1, 1
       cmp $t1, 0
       jnz _exit_while
    lbl_block:
       call _foo
       jmp lbl_while_condition
    

    whereas the for(;;) would compile in the first pass to:

    lbl_for_init:
       ; do nothing
    lbl_for_condition:
       ; always
    lbl_for_block:
       call foo;
    lbl_for_iterate:
       ; no iterate
       jmp lbl_for_condition
    

    i.e.

     lbl_for_ever:
        call foo
        jmp lbl_for_ever
    

    Hence saving 3 instructions on every pass of the loop.

    In practice however, both statements have long since been not only functionally equivalent, but also actually equivalent, since optimisations in the compiler for all builds other than debug builds will ensure that the mov, cmp and jnz are optimised away in the while(1) case, resulting in optimal code for both for(;;) and while(1).

提交回复
热议问题