News for hackers. Stuff that matters.
Re:Misconceptions about loops in C by akira2501 on Thursday June 27, 2024 @03:49PM (#40814338)
> A loop can always be expressed with tail recursion.

If I were writing the code in assembly, I would just use a loop, because that's what the machine is optimized to perform.

> But this is also a symptom of standard c's problem of not allowing one to define functions inside of functions.

There are extensions that do this; however, they cannot create a scoped closure for you so nobody cares to use them for anything.

> and these have to be coalesced into a single flag for the loop.

Or just use 'goto'.

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.
Re:Misconceptions about loops in C by murderfs on Thursday June 27, 2024 @04:05PM (#40814495)
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.
Re:Misconceptions about loops in C by WJW on Thursday June 27, 2024 @04:14PM (#40814588)
Fair point. The higher level languages have been leaking back down into assembly.
Re:Misconceptions about loops in C by orhmeh09 on Thursday June 27, 2024 @04:32PM (#40814768)
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.
Re:Misconceptions about loops in C by akira2501 on Thursday June 27, 2024 @05:51PM (#40815542)
> 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.