#defer always occure even with break/continue ?

1 messages · Page 1 of 1 (latest)

fluid valve
#

Here is a sample code:

fn listener_thread(self: *Listener) void {
    loop: while (!self.shutdown_issued.load(.acquire)) {
        defer std.time.sleep(5 * std.time.ns_per_ms); // avoid burning the cpu

        const connection = self.server.accept() catch |err| switch (err) {
            else => {
                continue :loop;
            },
        };

        _ = connection;
    }
}

My question is pretty simple: Does "defer" occure even dough I continued (or breaked) the loop ?

#

It technically WILL execute the defer instructions

#

since defer is defined as: "Defer is used to execute a statement while exiting the current block."

#

and here this code is technically exiting the block by continuing the loop

#

OR do I need to assign the label to the block instead of the loop, and break the block instead of the continuing the loop ?

#

I just tested by myself

#

For those who are still curious, defer occure even by breaking or continuing!
nice zig!

lofty gust
#

Defer is scope-based, so as long as control flow leaves the scope it'll run.
I say "control flow", because if you call a function that never returns, then "control flow" obviously never will leave the scope. (It merely goes into the function and never comes back.)