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;
}
Re: Friday C Quiz: Know Your Closures
I don't know why (perhaps because it is yet another Friday night looking at this blog and I'm losing it ;-), but the first thing that I thought of with this: can I paste this into a browser and see the output?
The reason is probably that I don't have a C compiler installed and don't really want to get one.
I wonder if there is a C 'compiler' in Javascript? It seems like there is an emulator for everything these days.
Re: Friday C Quiz: Know Your Closures
You can trust DJ.
C:\Downloads>dir program.exe
Volume in drive C has no label.
Volume Serial Number is 2807-627C
Directory of C:\Downloads
04/05/2008 09:10 PM 46,476 program.exe
1 File(s) 46,476 bytes
0 Dir(s) 12,765,540,352 bytes free
C:\Downloads>program.exe
8
C:\DOWNLO~1>
Re: Friday C Quiz: Know Your Closures
Re: Friday C Quiz: Know Your Closures
error: nested functions are disabled, use -fnested-functions to re-enable
Good error message. I try it again with enabled nested-functions and run. The program prints:
8
Hmmm. So, I stick a small printf as the first line of the embedded "fib()" to see the value of n on entry.
Even more hmmmm...