Connecting Tech Pros Worldwide Forums | Help | Site Map

when to use recursion and is it better than a function ...in c?

Newbie
 
Join Date: Oct 2009
Posts: 1
#1: Oct 9 '09
which is better recursion or function ....???and when to use function ?and when to use recursion?

Banfa's Avatar
AdministratorVoR
 
Join Date: Feb 2006
Location: South West UK
Posts: 6,195
#2: Oct 9 '09

re: when to use recursion and is it better than a function ...in c?


Your question is unclear, a function is a language construct where as recursion is a programming technique (normally achieved using a function that can be called recursively), they are not comparable.

Did you mean which is better recursion or iteration?

You normally have better control of memory usage, particularly stack usage with iteration. On the other hand recursion often produces more elegant, and therefore more easy to maintain code.
myusernotyours's Avatar
Familiar Sight
 
Join Date: Nov 2007
Posts: 168
#3: Oct 9 '09

re: when to use recursion and is it better than a function ...in c?


Some problems also will lend themselves nicely to recursion. What you should avoid is a situation where you use recursion in an unintuitive manner. It becomes hard to read.
I also find that some situations are so naturally recursive that you don't even need to think deeply about all the paths at all but the end result is very elegant code if you check it out keenly.

Regards,

Alex.
Expert
 
Join Date: Mar 2008
Location: Naperville, Illinois U.S.
Posts: 831
#4: Oct 9 '09

re: when to use recursion and is it better than a function ...in c?


The only simple and universal answer to which is better, recursion or iteration, is ... it depends.

Recursion sometimes, but not always, yields simpler and more elegant source code. Simpler and more elegant source code is usually easier to review and easier to maintain. It may have a smaller footprint in executable memory. Each recursive invocation gets its own set of automatic variables, so the invocations are protected from unintended interactions with other invocations.

Iteration almost always uses less stack space and may run a little faster for nominal conditions. All iterations have equal access to the function's automatic variables so it is easier to make state information available to all iterations.

Which is better depends on your situation. For example, an embedded application may not be able to tolerate the possibly unbounded stack usage of a recursive function.
Reply


Similar C / C++ bytes