Skip to content

Allowed to use undefined in comparison #8056

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
ratfactor opened this issue Feb 23, 2021 · 3 comments
Open

Allowed to use undefined in comparison #8056

ratfactor opened this issue Feb 23, 2021 · 3 comments
Labels
bug Observed behavior contradicts documented or intended behavior stage1 The process of building from source via WebAssembly and the C backend.
Milestone

Comments

@ratfactor
Copy link
Contributor

Normally using undefined in a comparison produces a compiler error:

./foo.zig:9:9: error: use of undefined value here causes undefined behavior
    if(1==undefined) return;

But when using "this one weird trick" (comparing an optional pointer struct field), there are no errors and it compiles and runs:

const std = @import("std");

const Foo = struct{ a: ?*u8 = undefined };

pub fn main() void {
    var foo = Foo{};
    if(foo.a == undefined) std.debug.print("foo.a is undef {}\n",.{foo.a});
}
@LakeByTheWoods
Copy link
Contributor

It also works if a is a non-optional pointer: https://godbolt.org/z/vExKb7

@SpexGuy SpexGuy added bug Observed behavior contradicts documented or intended behavior stage1 The process of building from source via WebAssembly and the C backend. labels Mar 16, 2021
@Vexu Vexu added this to the 0.9.0 milestone Mar 19, 2021
@andrewrk andrewrk modified the milestones: 0.9.0, 0.10.0 May 19, 2021
@RetroDev256
Copy link
Contributor

RetroDev256 commented Sep 8, 2024

Confirmed this bug lack of error message is in self-hosted, 0.13+.

@tau-dev
Copy link
Contributor

tau-dev commented Feb 6, 2025

This has been fixed in master:

const std = @import("std");

const Foo = struct{ a: ?*u8 = undefined };

pub fn main() void {
    var foo = Foo{};
    const c: u8 = 1;
    if(foo.a == undefined) std.debug.print("foo.a is undef {}\n",.{foo.a orelse &c});
    _ = &foo;
}
/tmp/lol.zig:8:14: error: use of undefined value here causes undefined behavior
    if(foo.a == undefined) std.debug.print("foo.a is undef {}\n",.{foo.a orelse &c});
       ~~~~~~^~~~~~~~~~~~
referenced by:
    posixCallMainAndExit: zig-out/lib/zig/std/start.zig:647:22
    _start: zig-out/lib/zig/std/start.zig:464:40

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Observed behavior contradicts documented or intended behavior stage1 The process of building from source via WebAssembly and the C backend.
Projects
None yet
Development

No branches or pull requests

7 participants