6 ms·
If your assert compiles down to `if (condition) {}` in production then the compiler will optimize away the condition while keeping any side effects.
by nmilo 6mo ago
If your assert compiles down to `if (condition) {}` in production then the compiler will optimize away the condition while keeping any side effects.
- IshKebab 6mo agoYeah which may not be what you want. E.g. `assert(expensive_to_compute() == 0)`. The correct way to solve this is with debug asserts (as in Rust, or how the parent described).
- nyc_pizzadev 6mo agoGenuine question, does Rust know if `expensive_to_compute()` has side effects? There are no params, so could it be compiled out if the return value is ignored? Ex: `expensive_to_compute()` What about: `(void) expensive_to_compute()`?
- IshKebab 6mo agoNo, Rust is the same as C++ in terms of tracking side effects. It doesn't matter that there are no parameters. It could manipulate globals or call other functions that have side effects (e.g. printing).
- functional_dev 6mo agoWhat about rust const fn()? I think it guarantees there are no side effects
- IshKebab 6mo agoI think you're right. Equivalent to C++'s constexpr.
- aw1621107 6mo agoNo, in general Rust doesn't (and can't) know whether an arbitrary function has side effects. The compiler does arguably have a leg up since Rust code is typically all built from source, but there's still things like FFI that act as visibility barriers for the compiler.
- nmilo 6mo agoCompilers are very good these days. If it has no side effects it will likely be compiled out.