Alternative to function calling itself  
Author Message
Michael Dawson





PostPosted: Visual C# General, Alternative to function calling itself Top

For example when you need to go through a folder structure I just have a function call itself and do the same for each sub folder before handeling files. I know this is a bad way of doing it, but what is the best way of achieving this effect without self referencing functions

Any help or input will be appreciated.

Thank you :)



Visual C#19  
 
 
Paul Louth





PostPosted: Visual C# General, Alternative to function calling itself Top

There's nothing wrong with that.  It's called recursion.  However if you insist on doing it yourself then you can use a Stack to save your state, but it's far simpler to use the languages function stack.  The only gotcha is if you go really deep, and create a lot of data for each level.


 
 
nippysaurus





PostPosted: Visual C# General, Alternative to function calling itself Top

Is this fine because of the managed framework Like would it be ok to do this in C/C++ as well
 
 
Paul Louth





PostPosted: Visual C# General, Alternative to function calling itself Top

Perfectly fine on both.  Just depends on how much data you're sticking on the function stack for each recursion level.  So the idea is to limit the amount of local variables you create in the method.  If you go too deep, then you may get a StackOverflow exception, but if you're working with folders then you should be fine.
 
 
Paul Louth





PostPosted: Visual C# General, Alternative to function calling itself Top

And to further that, I find recursive functions to be a very elegant solution to traversal of tree structures. Certainly more elegant than managing the stack yourself!