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
11
u/aePrime May 22 '25
There are a few subtleties to navigate here. If the code is performance critical, iteration is often faster, but requires more bookkeeping by the programmer. As others have stated, for many functions, recursion is simpler and more elegant. There’s a tradeoff between programming time and run time. Also, the function may not be performance critical, and it’s fine to write it recursively. To get really esoteric, sometimes recursion is just as efficient as the iterative solution: when using tail calls, recursive functions don’t actually have to make another function call. Your results may vary depending on your language, virtual machine, and/or compiler.