#Weird, 'undefined' bool is false?

1 messages · Page 1 of 1 (latest)

safe anchor
#

Hi there, new here. A happy zig beginner. And I understood this is a good place to ask zig related programming questions.
I just discovered my undefined variables actually have a value. Is this to be expected?
I though undefined was a primitive value, so would have expected them to be 'undefined' ?


pub fn main() void {
    var undef: bool = undefined;

    std.debug.print("{}\n", .{undef});
    if (undef == false) {std.debug.print("Weird, undefined is false?\n", .{});} else std.debug.print("Undefined is not false but: {}?\n", .{undef});
}
#

Looking up how to apply formatting to my posts now... sorry.

dry jetty
#

undefined is essentially used to leave variables or fields uninitialized during assignment
In debug mode, the compiler will use 0xaa.. as the value and in release builds the undefined field/variable may be anything

#

It is a value that coerces to any type but you cannot check if some value is undefined
If you need to track if variable was assigned to you would use an optional type and initially assign it to null instead

safe anchor
#

Okay. Didn't know the second part. Interesting. Would I get notified somehow if my variables stay 'undefined' throughout the program?

#

Or would the program run with the undefined variables being anything

dry jetty
#

I don't think so, there is no way to track it
You should be very careful when using it, it should only be used when you are guaranteed to assign to the variable later before reading from it again (or are guaranteed to not use it later)

#

If you see 0xaaaaa pop up it is an indication you may have used an undefined value though

#

In this case it is even more confusing because of bool

safe anchor
#

Thanks for helping me out so promptly. Seems important that this behavior is more obviously put forward in the docs somehow? Or did I mis it completely.

dry jetty
#

I think it's mentioned in the assignment section

#

Anyway, no problem 🙂

safe anchor
#

🙂 got me then

#

Do I mark this as 'answered' somehow? Or leave it with a goodnight to you all?