Hacker News new | ask | show | jobs
by Animats 500 days ago
Not quite. "The central idea behind defer is that, unlike its Go counterpart, defer in C is lexically bound, or “translation-time” only, or “statically scoped”"

Defer in Go puts the deferred action on a run time to-do list that's processed at function exit. You can queue up deferred actions from a loop in Go. Not in this proposal for C.

What happens in this C proposal if you put a defer request inside a loop? Is it a compile time error, do they somehow to try to give it meaningful semantics, or is it undefined behavior?

3 comments

> What happens in this C proposal if you put a defer request inside a loop? Is it a compile time error, do they somehow to try to give it meaningful semantics, or is it undefined behavior?

The action runs at the end of the loop-body, before the next iteration. It does this because the loop-body is the enclosing block, and a defer will always run when its enclosing block ends. As described in the article, this is intentionally-so and makes it possible to acquire a mutex inside a loop while automatically releasing it before the next iteration, something which is easy to get wrong in Go.

Loops in C introduce a new lexical scope, so the defer runs once for every loop iteration.

Assuming you are using defer for destructor purposes, and use it where you declare your variable, this would generally be what you want, as it frees the memory at the same time it goes out of scope.

The flip side of this is that code like the following would be broken:

    char *foo = NULL;
    if (true) {
         foo = calloc(1,1);
         defer { free(foo); }
    }
    char c = *foo;
As foo gets freed at the end of the conditional, which is prior to the dereference.
That particular example is easy - just put the defer before the if.
Yes maybe you didn't get to the end of my one-sentence comment but I did say

> except they fixed the scoping issue

> What happens in this C proposal if you put a defer request inside a loop?

It executes at the end of the loop body.