Hacker News new | ask | show | jobs
by spc476 1461 days ago
I've used this method in C code. One reason---C89 only allows variable declarations at the top of a block, and if I have a small section of code towards the middle of end of the function with its own variable use, the declaration is separated from the use. By using a new scope, the declaration can be done right where it's used. Yes, it looks a bit weird, but there could be benefits.

I also use this in Lua. The benefit there---once the scope is over, the variables declared in the scope become available for garbage collection. In a small function, this isn't that much of a win, but for the top level scope, it probably is. You can see an example of this in my gopher server [1]. Don't let the formatting confuse you, this:

    local CONF = {} do
      local conf,err = loadfile(arg[1],"t",CONF)
      if not conf then
        io.stderr:write(string.format("%s: %s\n",arg[1],err))
        os.exit(exit.CONFIG,true)
      end
      -- rest of code
    end
is the same as

    local CONF = {} 
    do
      local conf,err = loadfile(arg[1],"t",CONF)
      if not conf then
        io.stderr:write(string.format("%s: %s\n",arg[1],err))
        os.exit(exit.CONFIG,true)
      end
      -- rest of code
    end
The 'do' keyword introduces a new scope (and can be used anywhere to do so). I format it as the former to be more explicit about the CONF variable being defined by the following code block.

[1] https://github.com/spc476/port70/blob/master/port70.lua#L41