zig icon indicating copy to clipboard operation
zig copied to clipboard

Language Reference imprecise about the behaviour of `undefined`

Open paoda opened this issue 3 years ago • 1 comments

Zig Version

0.10.0-dev.3981+60678f5ba

Steps to Reproduce

Given the example source:

const std = @import("std");

test "this passes" {
    var tmp: u8 = undefined;
    try std.testing.expect(tmp == 0xAA);
}

test "this fails" {
    const tmp: u8 = undefined;
    try std.testing.expect(tmp == 0xAA);
}

Expected Behavior

I expect both cases to pass because the language reference states that

In Debug mode, Zig writes 0xaa bytes to undefined memory. This is to catch bugs early, and to help detect use of undefined memory in a debugger.

However, the above code indicate that this is only true when a variable is mutable, which either is a compiler bug, or a detail I believe to be worth mentioning.

Actual Behavior

Given the current wording of the Zig Language Reference, I would expect both test conditions to pass, since in both situations, I am assigning undefined to a variable in Debug mode.

paoda avatar Sep 12 '22 11:09 paoda

undefined is a poison value; Comparisons to undefined produce bools that are undefined. Branching on undefined is undefined behavior and the compiler can tell you if you try if (undefined) directly.

Whether the 0xaa value is observable to code is up to the compiler since undefined allows the compiler to assume any value is there. I think it should be clarified in the lang. ref. that 0xaa is explicitly a code-gen nicety rather than an observable semantic.

kprotty avatar Sep 12 '22 16:09 kprotty