Re:Misconceptions about loops in C
by WJW on Thursday June 27, 2024 @03:59PM
(#40814445)
Do you mean a conditional jump? Because assembly doesn't know about loops. And recursion is basically a jump too, even more so if you manually do the TCO. They are literally equivalent.
[ Parent
| on HN ]
Depends on the assembly and depends on the loop. x86 has multiple instructions that hint at knowing about loops: e.g. the `loop` instruction that does a decrement and jump, and the rep prefixes that let you implement memcpyish functions in a single instruction.
Fair point. The higher level languages have been leaking back down into assembly.
For a very long time, even PDP7, on which C was created, with ISZ – Increment the memory operand and Skip next instruction if result is Zero.
> And recursion is basically a jump too, even more so if you manually do the TCO.
The recursion in TCO can be implemented with a jump but it requires an explicit stack frame and ultimately it must return a value through that stack frame. Basic loops have no such requirements which allows you to do things like jump from the middle of one loop into the middle of a different one.
Granted, this is rare, and rarely useful in practice, but it occasionally is and the burden of restructuring these forms into TCO would actually reduce their clarity and performance.
> They are literally equivalent.
They are /functionally/ equivalent. The literal differences are meaningful and have definite performance implications.