Evan Martin (evan) wrote in evan_tech,
Evan Martin
evan
evan_tech

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

  • more on bug tracking; distributed editing

    A few separate posts, all in the same area. 1) Most (all?) the distributed bug tracking software I've glanced at stores bugs in a directory, one…

  • dvcs and offline

    I got a couple of comments on that previous post that betray a bit of a misunderstanding about how collaborative projects work in the presence of…

  • distributed bug tracking

    Distributed bug tracking is the natural extension of distributed version control. Aside from the normal benefits of distributed version control, like…

  • Post a new comment

    Error

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