Skip to content

bug: Comptime variable assignment in branch with runtime condition #8462

Closed
@felipepiovezan

Description

@felipepiovezan

What

An assignment to a comptime variable is predicated by a run-time value, but the compiler doesn't emit an error.
Instead, it uses "program" order and performs assignments on all branches. In particular, flipping the branch
condition and inverting the branch blocks should produce an equivalent program, but it doesn't.

(This could be me misinterpreting the comptime documentation)

Code that reproduces the issue

Godbolt link

export fn foo(arg:i32) i32 {
   comptime var x = 0;
   x = 10000;
   if (arg > 0) { x = 1;}
   else {x = 2;}
   return x;
}

const std = @import("std");

pub fn main() !void {
    std.debug.print("foo(-1) = {}!\n", .{foo(-1)});
    std.debug.print("foo(1) = {}!\n", .{foo(1)});
    std.debug.print("foo(-1) = {}!\n", .{comptime foo(-1)});
    std.debug.print("foo(1) = {}!\n", .{comptime foo(1)});
}

Produced output

foo(-1) = 2!
foo(1) = 2!
foo(-1) = 2!
foo(1) = 1!

Expected output

// first print => error: writing to comptime variable on a path that depends on a runtime value
/// second print => error: writing to comptime variable on a path that depends on a runtime value
foo(-1) = 2!
foo(1) = 1!

Tags searched before filing this issue

comptime variable branch

Tested with Zig versions:

  • trunk (version available at the time of writing on Godbolt)
  • .7
  • .6

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions