Skip to content

Instantly share code, notes, and snippets.

@jackdbd
Last active April 16, 2023 14:36
Show Gist options
  • Save jackdbd/06fc24c3bbbe2988dd318bd0dcd2cb71 to your computer and use it in GitHub Desktop.
Save jackdbd/06fc24c3bbbe2988dd318bd0dcd2cb71 to your computer and use it in GitHub Desktop.
Integer overflow with custom integer in Zig
//! Integer overflow with custom int in Zig
//! build and run with:
//! zig build-exe integer_overflow.zig && ./integer_overflow
const std = @import("std");
pub fn main() void {
std.log.info("unsigned int (primitive type) [0, 7)", .{});
// usize is an unsigned pointer sized integer. See also: https://github.com/ziglang/zig/issues/5185
// usize is a primitive type:
// https://ziglang.org/documentation/master/#Primitive-Types
for (0..8) |i| {
std.log.debug("i: {}", .{i});
}
std.log.info("unsigned int (custom type) [0, 7)", .{});
// u3 is NOT a primitive type. It is a custom type.
var j: u3 = 0;
while (j < 7) : (j += 1) {
std.log.debug("j: {}", .{j});
}
std.log.info("unsigned int (custom type, overflow) [0, 7)", .{});
// overflow when k is 7 (111) and gets incremented to 8
var k: u3 = 0;
while (k < 8) : (k += 1) {
std.log.debug("k: {}", .{k});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment