top | item 25420221

(no title)

rseacord | 5 years ago

I've heard this comment more than once. What we are trying to accomplish is to collocate the resource acquisition code with the acquisition release code. This does mean that the release code is removed when where the release occurs (for example, at every location a function returns.

However, this is not without precedence in C. For example, just look at the for loop:

for (clause1; expression2; expression3) statement

expression3 is executed after statement.

discuss

order

simias|5 years ago

I would argue that the C for loop is a rather awkward construct. It's found its way in many languages, so I think most people are used to its idiosyncrasy but it's not great if you try to take a fresh look at it.

I think the best defense of this syntax is that it makes writing basic iteration a bit nicer without having to add boilerplate (the iconic `for (i = 0; i < n; i++)`) but then I would argue that the real problem is that C is severely lacking in the iteration department and this is a rather obvious hack (that languages like Javascript felt the need to copy wholesale, for some insane reason).

scythe|5 years ago

The nonlocality can be eliminated by replacing the `guard {}` block with a `resolve;` statement to be placed at the end of a block containing multiple `defer`s. This also reduces nesting and solves the question of where the `defer` is executed and makes it easy to grep to the location where the `defer` statement will be executed. Of course, it would be a syntax error to use `defer` without a following `resolve;`.