9.7 Recursive Functions


9.7 Recursive Functions

A function that calls itself is said to be recursive, and the process of doing this is called recursion. For example, the following function is recursive. In this case, it loops forever, so it's not advisable to run this program.

      void function1()      {         std::cout <<"hello world\n";         function1();   //calls itself here      } 

Although not explored in great detail here, recursive functions can be useful for searching and sorting data. For example, to search through the files and folders (the directory tree) of a computer, the following could be achieved using recursion:

  • A function has the declaration SearchFolder(FolderName).

  • Given a valid folder name, this function cycles through every subfolder and file contained in a given folder.

  • As it encounters each item, it prints its name on the screen.

This function, however, could be extended. By making this function recursive each time it encounters a new subfolder, it's possible for one function to recursively cycle through the entire directory tree and print the names of every file and folder on a single hard disk.




Introduction to Game Programming with C++
Introduction to Game Programming with C++ (Wordware Game Developers Library)
ISBN: 1598220322
EAN: 2147483647
Year: 2007
Pages: 225
Authors: Alan Thorn

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net