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.
103
Upvotes
View all comments
Show parent comment
1
u/purepersistence May 22 '25
Recursion will often require more memory because ALL of your local variables get allocated again on the stack whether they really need copying or not - and the return address/stack frame. With iteration you as a programmer control what gets copied and what does not.