r/computerscience • • May 22 '25

Discussion Why Are Recursive Functions Used?

Why are recursive functions sometimes used? If you want to do something multiple times, wouldn't a "while" loop in C and it's equivalent in other languages be enough? I am not talking about nested data structures like linked lists where each node has data and a pointed to another node, but a function which calls itself.

106 Upvotes

152 comments sorted by

View all comments

Show parent comment

1

u/AdamWayne04 May 22 '25

the code you've shown demosntrates neither functions nor recursive function calls

def sum(nums, length, accum):
  if length == 0: return accum
  else: return sum(nums[1..(length-1), length-1, accum + nums[0])

Is this what you're looking for? They're the same thing. Saying x = a; y = b; z = c; call f is no different from f(a,b,c) besides notation, and if the code here was compiled, it could very reasonably produce an assembly simillar to the one above (without the syntax sugar of course).

This is the literal definition of a recursive function that, in fact uses no call stack. The only storage required is the return address in the %ra registry (and the memory required to store the array, obviously).

1

u/zenidam May 22 '25

From an algorithmic perspective, what you say makes sense; there is no meaningful difference between the two codes. From a language design perspective, the differences in syntax (and the compiler/interpreter structures needed to support these differences) are the point.