As opposed to... entire program scoped?
loop i over whatever {
defer foo(i)
}
I.e. a loop's iterations can put things into the defer list, which is then executed when the function exits. Whereas if the defer list were block scoped, then each defer would execute immediately on the termination of its enclosing iteration.Also, there is problem with conditional defers like:
if (condition)
defer whatever
Okay, so that is in the surrounding scope. Now I need to add some piece of logic: if (condition) {
defer whatever
piece of logic
}
Now it's scoped to the curly braces and executes immediately after "piece of logic" is done?In terms of performance, the defer list has to be an actual run-time object; the compiler can't always optimize away the existence of the defer list. If defer is block-scoped and used in numerous nested scopes of the same function, where the compiler isn't able to remove it, then you get multiple defer list instantiations in the function's stack frame, which is a kind of bloat. These have to be initialized to the empty state on each entry into a block. At most defer list to initialize on entry into a function is less time and space overhead.
A more flexible design would be defer to work with named blocks:
foo: {
bar: {
defer h() foo;
defer g() bar;
defer f();
}
}
h() is deferred to the termination of foo (thus using foo's defer list); likewise g() in relation to bar, and the f() defer is function scoped.