Division by zero and Illegal Behavior

Most of your questions are answered in the same document you linked. https://ziglang.org/documentation/0.14.1/#Division-by-Zero has example program outputs that shows what happens when you divide by zero at comptime or at runtime in safety-checked builds, and the operator table lets you know that dividing floats by zero under @setFloatMode(.optimized) is illegal behavior:

Name

Syntax

Types

Remarks

Example

Division

a / b
a /= b

10 / 5 == 2

What’s not mentioned in the docs is that you’re not allowed to divide comptime_float by 0 and that this is always a compile error. comptime_float has the same precision as f128 but it’s only intended for storing finite values. You can currently store infinity/NaN inside a comptime_float with some trickery but there is an accepted proposal to disallow this.

Also relevant: @setFloatMode(.optimized) will be replaced by a set of new float types which are distinct from IEEE 754 floats like f32 and which will only allow finite values (which means that dividing values of those types by zero will be illegal behavior).

“ln” is std.math.log(). There’s also @log(), @log2() and @log10().

The behavior for most math functions is specified by IEEE 754. sqrt(-1) is NaN, log(0) is -inf and log(-1) is NaN. For the new float types I mentioned above I would assume that all non-finite results will be illegal behavior.

3 Likes