Recursion help

closed account (4ET0pfjN)
Hi, why does the base case end w/ a semi-colon, and I didn't know you can have void type do: return sum(...)

this is the code I am trying to understand that I found online:
1
2
3
4
5
6
7
8
9
10
void sum( int arr[], int n, int & result )
{
   if ( n == 0 )  // base case 1
     ; // nothing to do, result has answer
   else
     {
       result += arr[ n - 1 ];
       return sum( arr, n - 1, result );
     }
}
You have to put a statement after the if statement that will run if the condition is true. Placing the semicolon with nothing before it makes an empty statement that do nothing.

I would say changing line 3-5 to if ( n != 0 ) makes more sense to me but both ways work and there is no difference in what the program does.

return sum( arr, n - 1, result );
apparently you can do this but it doesn't make much sense. sum has no return value so there is nothing to return. In this case you can just remove the return keyword if you want.

Last edited on
Topic archived. No new replies allowed.