Evan Martin (evan) wrote in evan_tech,
Evan Martin

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.

  • blog moved

    As described elsewhere, I've quit LiveJournal. If you're interested in my continuing posts, you should look at one of these (each contains feed…

  • dremel

    They published a paper on Dremel, my favorite previously-unpublished tool from the Google toolchest. Greg Linden discusses it: "[...] it is capable…

  • treemaps

    I finally wrote up my recent adventures in treemapping, complete with nifty clickable visualizations.

  • Post a new comment


    default userpic
    When you submit the form an invisible reCAPTCHA check will be performed.
    You must follow the Privacy Policy and Google Terms of use.