Skip to content

integer overflow with new for loop #14700

@IntegratedQuantum

Description

@IntegratedQuantum

Zig Version

0.11.0-dev.1711+dc1f50e50

Steps to Reproduce and Observed Behavior

const std = @import("std");

pub fn main() void {
	var start: u32 = 1;
	var end: u32 = 0;
	for(start..end) |x| {
		std.log.info("{}", .{x});
	}
}

output:

$ zig run test.zig
thread 28234 panic: integer overflow
/home/mint/Desktop/test.zig:6:6: 0x20b56c in main (test)
 for(start..end) |x| {
     ^
/home/mint/Downloads/zig/lib/std/start.zig:607:22: 0x20aa25 in posixCallMainAndExit (test)
            root.main();
                     ^
/home/mint/Downloads/zig/lib/std/start.zig:376:5: 0x20a4d1 in _start (test)
    @call(.never_inline, posixCallMainAndExit, .{});
    ^
Aborted (core dumped)

Expected Behavior

I would expect these two loops to behave equivalent:

for(start..end) |x| {
	...
}
// should behave like
var x: usize = start
while(x < end) : (x += 1) {
	...
}

And therefor no integer overflow should happen.

workaround for anyone else who stumbles over this

for(start..@max(start, end)) |x| {
	...
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions