Reputation: 13
Is the recursive call in my code a tail call or is it just ordinary recursion?
void sum(const int values[], size_t count,int* result){
if(count <= 0) return;
*result += values[0];
sum(values + 1,count - 1,result);
}
Because as far as I know, a tail call is recursion that occurs as the last call in a function.
Upvotes: 1
Views: 113
Reputation: 36680
Given that C does not require tail-call elimination/optimization, your safe strategy is to avoid recursion where it doesn't naturally fit (think of things like binary search trees).
In your specific case, there's no reason not to write:
void sum(const int *values, size_t count, int *result){
for (size_t i = 0; i < count; i++) {
*result += values[i];
}
}
As an aside: it's interesting that you're using recursion but then modifying a pointer, which is very much not functional. This has the effect that for a sum to be accurate the value result
points to must be initialized to 0
or the result will be inaccurate.
Upvotes: 2
Reputation: 386676
If no code follows a call, it's a tail call.
In C, this would like one of these:
void g( … );
void f( … ) {
…
g( … ); // Tail call.
}
void g( … );
void f( … ) {
…
g( … ); // Tail call.
return;
…
}
T g( … );
T f( … ) {
…
return g( … ); // Tail call.
…
}
It has nothing to do with recursion, but it does include recursive calls.
Tail calls are interesting since they can be eliminated. C neither mandates nor forbids tail-call elimination. That's up to the compiler.
Upvotes: 1