Well, you can recreate the behavior of the example loop with just one (conditional) jump because we already know that 0<10. Though admittedly a compiler would probably not use that shortcut. Also, this seems to be something specific to the “while” loop, e.g. you can do a “for” loop with just one jump.
A sophisticated compiler absolutely would use that shortcut. Interestingly, it would figure out the shortcut by translating to an intermediate language that is neither the original language nor assembly, in which the transformation is more obvious.
It seems to me, that Dacyn’s code executes [stuff] at least once for any n. But iff n <= 0, original while loop does not execute its body. Dacyn’s code looks like a do-while loop.
Well, you can recreate the behavior of the example loop with just one (conditional) jump because we already know that 0<10. Though admittedly a compiler would probably not use that shortcut. Also, this seems to be something specific to the “while” loop, e.g. you can do a “for” loop with just one jump.
A sophisticated compiler absolutely would use that shortcut. Interestingly, it would figure out the shortcut by translating to an intermediate language that is neither the original language nor assembly, in which the transformation is more obvious.
Good point, I’ll change 10 to n in the post.
How do you implement a “for” loop from 0 to n with one jump, if n isn’t known and can be 0?
i=0
Label 1
[stuff]
i=i+1
If i ⇐ n
Goto 1
I meant a “for” loop with i < n...
What’s wrong with the implementation Dacyn gave?
It seems to me, that Dacyn’s code executes
[stuff]
at least once for anyn
. But iffn <= 0
, originalwhile
loop does not execute its body. Dacyn’s code looks like ado-while
loop.Oh right. For loops check the condition before entering the body, just like while loops and unlike do-while loops. Thanks.