Undefined Optionals

Hello, I have two questions about how optional values and undefined interact:

  1. Will @as(?u32, @as(u32, undefined)) != null always be true?
  2. Will @as(?u32, undefined) != null always be true?

I am pretty sure that Q.2 is not guaranteed, but how about Q.1?

The result of anything you interpret undefined as is undefined(not defined) and the equality of that value to any other value is also undefined(not defined).
1&2. It may always be true, always be false, and(sic) sometimes be true. The ?u32 you receive has no meaningful value and it is undefined to branch on.

3 Likes
  1. Yes. Only the u32 part is undefined. The ? part is defined not null.
test {
    try std.testing.expect(@as(?u32, @as(u32, undefined)) != null);
}
test {
    // will fail
    try std.testing.expect(@as(?u32, @as(u32, undefined)) == null);
}
  1. No. It is not == null either. It is Illegal to read undefined.
test {
    // will fail
    try std.testing.expect(@as(?u32, undefined) != null);
}
test {
    // will fail
    try std.testing.expect(@as(?u32, undefined) == null);
}

But if you make sure that optional is runtime-known you skip compile-time safety check:

test {
    var optional: ?u32 = undefined;
    try std.testing.expect(optional != null); // unchecked Illegal Behavior
    optional = 0; // suppress compiler error
}
1 Like

Undefined is not the same as null. There are better explanations, but the way I understand it is that when the variable is set as undefined, the caller must guarantee that it had been set prior to using it.

1 Like

You can think of ?u32 as Optional = struct { is_null: bool, val: u32 }

  1. is equivalent to Optional{ .is_null = false, .val = undefined }
  2. is equivalent to @as(Optional, undefined)
1 Like