<< April 3, 2008 | Home | April 5, 2008 >>

Friday C Quiz: Know Your Closures

You know what? This closure thing has gotten into my head. I know it's pointless and useless to think and talk about it all the time, but I can't help it.

Well, my loss is your gain. And today's Friday quiz will take you all the way back to C. Yes, old trusty C! Although ANSI C does not support closures, some C compilers provide nested function extensions that provide a limited subset of closure functionalities such as accessing variables in the outer function.

Q: Will the following C program compile and run under your C compiler? If so, what will it print?


  #include <stdio.h>
  
  int main() {
    int (*pFib)(int);
    int fib(int n) {
      return n == 0 ? 0 :
             n == 1 ? 1 :
             pFib(n - 1) + pFib(n - 2);
    }
    pFib = fib;
    printf("%d\n", pFib(6));
    return 0;
  }