Hacker News new | ask | show | jobs
by TickleSteve 3820 days ago
locality.

It makes the code more readable.

1 comments

C90 allows declarations (almost) anywhere; you just have to use an explicit binding construct, which in C consists of a statement block. That is, instead of this:

  {
    int x = 3;

    do_something();

    int y = 4;

  }
you write this:

  {
    int x = 3;

    do_something();

    {
      int y = 4;
    }
  }
As a Lisp programmer, I prefer clear binding constructs which put the variables in one place. The (define ...) in Scheme that you can put anywhere makes me cringe; you have to walk the code to expand that into proper lambdas before you can analyze it. Other Lisp programmers don't agree with me. The CLISP implementation of Common Lisp, whose core internals are written in C and which historically predates C90, let alone C99, uses a "declarations anywhere" style on top of ANSI C. This is achieved with a text-to-text preprocessor called "varbrace" which basically adds the above braces in all the right places.

You get better locality with explicit binding blocks, because their scope can end sooner:

   {
     foo *ptr = whatever();
     /* this is a little capsule of code */
     /* scope of ptr ends */
   }

   {
     foo *ptr = whatever_else(); /* different ptr */
     /* this is another little capsule of code */
   }
These tighter scopes are much more tidy than the somewhat scatter-brained "from here to the end of the function" approach.

I can look at that capsule and know that that ptr is meaningful just within those seven lines of code. After the closing brace and before the opening one, any occurrence of the name "ptr" is irrelevant; any such occurrence refers to something else.