Actually arithmetic is even less defined in Zig than in C! For example, addition with unsigned integers in C is well-defined, but it is (safety-protected) undefined behavior in Zig.
I actually agree with you that the most obvious way should emphasize correctness over speed, and that's why +, -, /, and * operators have language-level assertions to protect against integer overflow - which is almost always a bug.
If Muon only has well-defined arithmetic, then it would not be able to catch this bug:
const std = @import("std");
test "contrived example" {
const income = 1000;
const taxes = 1009;
const cost_of_living = 300;
std.testing.expect(!isValidSalary(income, taxes, cost_of_living));
}
fn isValidSalary(income: u32, taxes: u32, cost_of_living: u32) bool {
return (income - taxes) > cost_of_living;
}
In Zig the output is: Test 1/1 contrived example...integer overflow
/home/andy/dev/zig/build/test.zig:11:20: 0x204267 in ??? (test)
return (income - taxes) > cost_of_living;
^
/home/andy/dev/zig/build/test.zig:7:38: 0x2040d8 in ??? (test)
std.testing.expect(!isValidSalary(income, taxes, cost_of_living));
^
It shows you right where the bug is. If the `-` was defined to be twos complement wraparound, isValidSalary would silently return the wrong data!Note that if you build this zig code in ReleaseFast or ReleaseSmall mode, it would be actually undefined behavior. ReleaseSafe is available as a build mode that has both optimizations and safety on.