Functions calling themselves...?

This is a discussion on Functions calling themselves...? within the C++ Programming forums, part of the General Programming Boards category; is it legal for a function to call itself as in:
int sum(int n)
{
if(n==0)
return 0;
else
n+sum(n-1);
...

not exactly, a recursive function works because it essentially creates a new instance of all of the automatic variables each time it's called. To stop it from calling itself it needs a condition to return and go back through each instance in reverse order.

Maybe it's just me, but it seems more effieient to use loops instead of recursion; sure they involve more code but they don't use all that stack space. So for what reasons do we use recursion other than to shorten code?

Hehe I'm a newbie and I don't understand some of that code, but yes I can see how much it shortens and eases the code. But isn't recursion really clunky and inneficient when it is run (especially with large numbers) because it uses so much stack space? So it won't work well at all in scenarios using much more data?

It depends on how deep the recursion gets. For a balanced tree with n elements, a tree traversal like that will only require O(lg(n)) (for 1000 elements, it would take have about 10 function calls on the stack at one time maximum, for 1000000 elements, it would take about 20 function calls on the stack max) stack space, which basically means that the function can handle an extremely large amount of data before stack space really needs to be taken into consideration, and by the time you have to worry about stack space, you've probably already exhausted the conventional memory with the data. They wrote it from the point of view of optimizing for small computers, hand helds, gameboy, etc, in which the stack is generally limited.