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.

  • dremel

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

  • your vcs sucks

    I've been hacking on some Haskell stuff lately that's all managed in darcs and it's reminded me of an observation I made over two years ago now (see…

  • google ime

    Japanophiles might be interested to learn that Google released a Japanese IME. IME is the sort of NLP problem that Google is nearly uniquely…

  • 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.