Iterating over all unsigned integers in a for loop

前端 未结 6 666
后悔当初
后悔当初 2020-12-07 01:09

Let\'s say I want to iterate over all integers in a for loop. For the sake of discussion, assume I am calling some unknown function f(unsigned x) f

6条回答
  •  天命终不由人
    2020-12-07 02:08

    You can do it with a do-while loop, but you lose all the niceties of the for syntax.

    It is still doable with do-while loop by using an anonymous block scope:

    {
        unsigned i = 0;
        do { f(i); } while (++i != 0);
    }
    

    While this construct may not be most idiomatic, it is an obvious candidate for clear assembly code. For example, gcc -O compiles it as:

    .L2:
            mov     edi, ebx   ; ebx starts with zero
            call    f
            add     rbx, 1
            cmp     rbx, rbp   ; rbp is set with 4294967296
            jne     .L2
    

提交回复
热议问题