Home > Net >  Why can't C (nor C ) optimize this recursive experiment?
Why can't C (nor C ) optimize this recursive experiment?

Time:07-13

I was thinking about functional programming techniques, recursions, and constness, and linked lists, so I made two experiments to test my compiler. In theory the compiler should be capable of optimizing away tail recursion (I now realize the functions provided here are NOT tail recursive and I apologize for trying to sneak them by as if they are, the actual tail recursive variants can be found in an answer I posted below) and produce a result at compile time without even building the structures in the first place at runtime.

It works as expected on the array variant below:

/**
 * @file test1.c
 */

static inline int my_array_sum(const int n, const int * const xs) {
    if (n == 0) {
        return n;
    } else {
        return n   my_array_sum(n - 1, xs   1);
    }
}

int main(int argc, char **argv)
{    
    const int xs[] = {1, 2, 3, 4, 5, 6, 7, 8};
    const int n = 8;    
    const int sum = my_array_sum(n, xs); 

    return sum;
}

producing the following object code (gcc test1.c -o test1.obj -c -O3, objdump -D test1.obj):

In MinGW/MSys 64bit:

0000000000000000 <main>:
   0:   48 83 ec 28             sub    $0x28,%rsp
   4:   e8 00 00 00 00          callq  9 <main 0x9>
   9:   b8 24 00 00 00          mov    $0x24,           
  • Related