# Division by zero and Illegal Behavior

**URL:** <https://ziggit.dev/t/division-by-zero-and-illegal-behavior/10961>\
**Category:** Help\
**Tags:** language, standard-library\
**Created:** [July 13, 2025, 7:16pm UTC](https://ziggit.dev/t/division-by-zero-and-illegal-behavior/10961 "2025-07-13T19:16:10Z")\
**Posts on this page:** 1\
**Showing post:** 1

<div class="post-metadata">

**Author:** ![jbe](https://ziggit.dev/letter_avatar_proxy/v4/letter/j/f6c823/32.png) [@jbe](https://ziggit.dev/u/jbe)\
**Post date:** [July 13, 2025, 7:16pm UTC](https://ziggit.dev/t/division-by-zero-and-illegal-behavior/10961/1 "2025-07-13T19:16:10Z")

</div>

I want to do some numerical calculations (probably using `f64`, but maybe I’ll be generic later). Some of my calculation may be subject to numerical instability, and I might run into

- division by zero
- square root of negative number
- sine of infinity
- logarithm of zero
- logarithm of negative number
- …

Now reading the Zig documentation on [Illegal Behavior](https://ziglang.org/documentation/0.14.1/#Illegal-Behavior), I read that

> [Division by Zero](https://ziglang.org/documentation/0.14.1/#Division-by-Zero)

is illegal behavior. I also read that:

> Some Illegal Behavior is _safety-checked_: […] All other Illegal Behavior is _unchecked_, […]

Some questions:

1. So is division by zero safety-checked or not? And how can I know?
2. Is division by zero also illegal behavior for floating point numbers, or just for integers?
3. If yes, does floating point division-by-zero differ from integer division-by-zero with regard to safety checking?
4. Are there differences between `comptime` and runtime?

Experiments with zig version `0.15.0-dev.936+fc2c1883b` on FreeBSD, all in `Debug` mode:

`std.debug.print("{}\n", .{1.0 / 0.0});`  
&nbsp;⇒ `error: division by zero here causes illegal behavior`

But:

```zig
for (0..3) |i| {
    const f: f64 = 1 - @as(f64, @floatFromInt(i));
    std.debug.print("{}\n", .{1.0 / f});
}

```

Results in:

```plaintext
1e0
inf
-1e0

```

Note that the documentation of [`@setFloatMode`](https://ziglang.org/documentation/0.14.1/#setFloatMode) says:

> ```zig
> @setFloatMode(comptime mode: FloatMode) void
> 
> ```
> 
> Changes the current scope’s rules about how floating point operations are defined.
> 
> - `Strict` (default) - Floating point operations follow strict IEEE compliance.
> - […]

Now IEEE says that `1.0/0.0` is `inf` by default, right? (But maybe IEEE allows optional exceptions?)

* * *

Also I wonder: Disregarding what Zig does now, would it be _good_ to treat floating point division-by-zero as Illegal Behavior?

If yes, then what about:

- `sqrt(-0.00001)`
- `ln(0)`
- `ln(-1)`
- …

And side question: Is there a reason why there is no _natural logarithm_ (of a number `x`, not of `1+x` or `gamma(x)`) in [`std.math`](https://ziglang.org/documentation/0.14.1/std/#std.math)?

---

_[View the full topic](https://ziggit.dev/t/division-by-zero-and-illegal-behavior/10961)._
