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/DawnOnTheEdge May 24 '25 edited May 24 '25

Clang has that: [[clang::musttail]] or __attribute__((musttail)). Rust is adding it as become.

Some compilers are in fact able to recognize that tail recursion works modulo any associative binary reduction operation (e.g., addition, multiplication, and, or, xor, concatenation, etc.) and refactor certain non-tail recursive functions into the equivalent of a while loop with accumulator. Functional programmers have traditionally just been expected to recognize when a call is tail-recursive-modulo-cons or not. But I agree, a keyword to force the optimization even in debug builds and make it an error, and flag it as a bug when you meant to write tail-recursion but actually didn’t, is a great idea.