r/computerscience • u/ShadowGuyinRealLife • 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
View all comments
Show parent comment
1
u/tmzem May 24 '25
Loops are definitely safer then recursion, since you don't risk a stack overflow (or arbitrary memory usage if your language supports growing call stacks/laziness).
The main feature of loops (one that functional programmers tend to ignore/downplay) is the guarantee of performing n loop iterations with O(1) stack space used for local variables. Doing the same with recursion will generally need O(n) stack space, as every iteration passes a copy of the updated local state down the call stack. To recover the O(1) behavior, many functional languages provide guaranteed tail call optimization. However to get it right, you have to convince yourself that the recursive call used for iteration is actually in tail position. This is a mental burden, as proving to yourself a call is in tail position is not always trivial, and even worse, any refactor might break the expected O(1) behavior, unless your programming language has some kind of "tailcall" keyword that errors out if function calls annotated with it are not actually in tail position (but you still need to remember to use it).
Therefore, I use: