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