Previous Entry Share Next Entry
11:39 am, 30 Nov 04

shadowing fun

I've mentioned this quirk before, but I still find it amusing: variable initializations in C can refer the the variable itself. In other words, every let works like a letrec.

So I can do stuff like:
char *crazy = malloc(strlen(crazy) + 1); /* make crazy exactly as big as it ought to be. */

This has the effect that you can't shadow a variable with a variable defined in terms of the shadowee.
Code like this:
int t = 0;
int t = t + 1;
printf("t %d\n", t);

Doesn't print out 1 unless you're lucky. While this seems like a crazy thing to do, I find it's a pretty common idiom in ML (where you don't need to create a nested scope to shadow) for when you're functionally updating something.

A C analogy might be something like, for example,
p = sprintf(buf, [...]);
p = sprintf(p, [...]);
p = sprintf(p, [...]);

where mutating p isn't really the goal.