#Ziglings 38 undefined variable

1 messages · Page 1 of 1 (latest)

glad talon
#

I am working my way through Ziglings and I am currently on exercise 38. Here is part of the exercise:

var chars: [2]Character = undefined;
// Glorp the Wise
chars[0] = Character{
    .role = Role.wizard
    .gold = 20,
    .health = 100,
    .experience = 10,
};

// Please add "Zump the Loud" with the following properties:
//
//     role       bard
//     gold       10
//     health     100
//     experience 20
//
//Feel free to run this program without adding Zump. What does
//it do and why?
// Printing all RPG characters in a loop:                                                                          
for (chars, 0..) |c, num| {
    std.debug.print("Character {} - G:{} H:{} XP:{}\n", .{
        num + 1, c.gold, c.health, c.experience,
    });
}

In this case, I never set the value at index 1 in the array.
When I compile and run it prints Character 2 - G:2863311530 H:170 XP:2863311530 which is 0xAAAAAAAA and is the default value for undefined memory.

My question is, why does this compile and run without warnings/errors/runtime crash?
to read an undefined value should not be allowed, or?

rocky harbor
#

Because 0xAA... is a debug value, is not undefined behaviour to print undefined value, is an undefined behaviour to control flow over undefined values

#

if you did an IF or something on undefined, that's undefined, behaviour, if you had it in a ptr, etc.

#

0xAAAA is just a pattern easy to spot

#

As you can see, you noticed that it was 0xaaaa quite easily

#

Now you know that value is undefined