The thing that i don t understand here is how can you put a FUNCTION that hasn t yet evaluated into a integer(will evaluate later but at the moment of the recursion it hasn t) into a int variable? Once n equals 0 the int smallResult will get populated but what happens in the memory and how can an int hold a FUNCTION for example for the first recurssive call that would be smallResult=sum(arr,n-1); the function sum(arr,n-1) did not evaluate yet (will afterwards).

int sum( int arr[], int n )
{
  if ( n == 0 )
    return 0;
  else 
    {
       int smallResult = sum( arr, n - 1 );  // A
       return smallResult + arr[ n - 1 ];
    }
}

this is what i understand and how i would do it everytime (it gives the same result)

  int sum( int arr[], int n )
    {
      if ( n == 0 )
        return 0;
      else 
        {
           return sum( arr, n - 1 )+ arr[ n - 1 ];
        }
    }

int smallResult = sum( arr, n - 1 );
Is not storing the function into the integer, it is storing the results of evaluating the function into the integer.
At runtime, your program will evaluate the code of sum and place the ultimate answer into smallResult. This is why it is terribly important to have a terminating condition in your recursion. Without it, you will never actually return and you will overflow your stack.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.