Skip to content

std.debug.assert causes evaluation of expression in release modes #10942

@leecannon

Description

@leecannon

Rather than a bug this is a question of the intended use of std.debug.assert.

One of the things I use assert for is to do expensive validation of state in debug builds expecting it to have no cost in a release build.

However that is not true of std.debug.assert as even in release fast the expression is fully evaluated. This is not what assert does in c.

Example in zig

const std = @import("std");

pub fn main() !void {
    std.debug.assert(expensiveFunction());
}

fn expensiveFunction() bool {
    std.io.getStdOut().writer().print("expensiveFunction ran\n", .{}) catch unreachable;
    return true;
}
$ zig run example.zig -ODebug
expensiveFunction ran
$ zig run example.zig -OReleaseFast
expensiveFunction ran

Example in c

#include <assert.h>
#include <stdbool.h>
#include <stdio.h>

bool expensiveFunction(void) {
    printf("expensiveFunction ran\n");
    return true;
}

void main(void) {
    assert(expensiveFunction());
}
$ zig run example.c -lc -ODebug
expensiveFunction ran
$ zig run example.c -lc -OReleaseFast

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions