-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
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
for loop on undefined variable falls into infinite loop (should throw an error or terminate immediately) #13934
Comments
Setting something to undefined means that the value can be absolutely anything. If you want pub fn init(win: *Window) Layout{
var result = Layout{
._view = ViewBase.init(win)
};
result._views.len = 0;
return result;
} |
Or, even better, initialize it to a zero length slice. This is what, for example, Line 57 in 0b4461d
In your case, you'd want: _views: []IView = &[_]IView{}, By the way, in the future, it'd be better to seek help with problems like this in one of the community spaces first: https://github.com/ziglang/zig/wiki/Community |
Thanks, since this works as expected, then I thought this is just a bug. const Foo = struct {
arr: []u8 = undefined,
fn foo(self: Foo) void {
print("undefined arr.len = {}\n", .{self.arr.len});
for (self.arr)|a|{
print("{}\n", .{a});
}
}
};
test "array undefined" {
const f= Foo{};
f.foo();
} |
My problem was not that I wanted len==0. |
Setting |
I see, I misunderstood that in the case of
Then I thought this is a undefined behavior of for loop. This is because if an undefined variable represents nothing, it seems strange for a for loop to work on a variable that represents nothing. The for loop should exit without executing the loop if the given variable is undefined, or should throw an error. |
|
Thanks for the explanation.
|
That's a strategy to make it noticeable to humans while debugging, since you'll very rarely have that byte pattern in normal code, but it's still a valid value. You can set a |
I'm sorry, I may have misunderstood. Is it a for loop you are talking about? |
I'm just talking about |
Wouldn't this be a useful safety check in debug mode? Is there a situation where a |
It would be, that's why #211 exists. |
pub fn draw(self: Layout) void {
for (self._views) |i| {
_ = i;
}
} pub const IView = packed struct { btw, with |
Zig Version
0.11.0-dev.753+331861161
Steps to Reproduce and Observed Behavior
Expected Behavior
expected it prints like this
This works.
Also this.
The text was updated successfully, but these errors were encountered: