Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Zig call defer after block breaks?

Tags:

zig

Given the following snippet, does the call to unlock occur after the break or before?

var input_data: InputState = blk: {
    user.input_mutex.lock();
    defer user.input_mutex.unlock();
    break :blk user.input;
};
like image 630
SilbinaryWolf Avatar asked Jul 21 '26 12:07

SilbinaryWolf


2 Answers

The documentation says:

defer will execute an expression at the end of the current scope.

It's not worded very clearly, but it means that the defer statements are executed after all of the code in the current block has been executed. This includes break statements.

For example, an errdefer statement cannot be executed before the last line, because errdefer statements are only enabled after return error.SomeError, which would be the last line in a function.

like image 200
sigod Avatar answered Jul 24 '26 04:07

sigod


Yes, at least as of zig version 0.12.0-dev.167+dd6a9caea

Running the following snippet:

const std = @import("std");

fn getRandom() !u64 {
    var seed: u64 = undefined;
    try std.os.getrandom(std.mem.asBytes(&seed));
    std.debug.print("test seed: {}\n", .{seed});
    return seed;
}

pub fn main() !void {
    var value = blk: {
        defer std.debug.print("defer test seed\n", .{});
        break :blk try getRandom();
    };
    _ = value;
}

Will show the following in console output:

test seed: 6866361107008308078
defer test seed
like image 31
SilbinaryWolf Avatar answered Jul 24 '26 06:07

SilbinaryWolf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!