A dream of recursion.

What is stack?

Stack is a special area of the computer memory which stores temporary variables created by a function. Is stack, variables are declared, stored and initialized during runtime. It is a temporary storage memory. When the task is complete, the memory of the variable will be erased.

What is heap?

The heap is the actual memory space available for the computer’s CPU to use. It is restricted only by the actual physical limits of the computer you are working on.

Ok, and then, what is recursion?

Let’s make use of our good old mate Wikipedia:

float _pow_recursion(float x, float y)
{
if (y == 0)
return (1);
if (y < 0)
return (_pow_recursion(x, y + 1) / x);

return (_pow_recursion(x, y - 1) * x);
}
_pow_recursion(2, 3).
if (y == 0)
return (1)
if (y < 0)
return (_pow_recursion(x, y + 1) / x);return (_pow_recursion(x, y - 1) * x);
if (y == 0)
return (1);
return (_pow_recursion(x, y — 1) * x);

Wrapping up:

While the example we used here was quite simple, the core concept could be applied to much more complicated functions and would still be valid. A recursive function WILL continue to call itself until a base case is met. This lead us to the evident conclusion that we should be really careful about memory usage when implementing recursive functions, as if the base case is not met, the function will keep keep calling itself causing what is known as stack overflow (which is also the name of probably the favorite website for all programmers in the world). When this happens, our computer, which ultimately has physical boundaries regarding the amount of information it can process, will eventually crash and the process will terminate without returning the expected result.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store