Search code examples
crecursiontail-recursion

Will this be a tail call or not?


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.


Solution

  • 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.