February 05, 2016
On Friday, 5 February 2016 at 08:45:00 UTC, Minas Mina wrote:
> Use assertions when a variable's value should not depend on external factors.
> For example, let's say you want to write a square root function.
> The input must be >= 0, and because this depends on external factors (e.g. user input), you must check it with `enforce()`.

Or alternatively, you could place the responsibility of ensuring that precondition on the caller, in which case you'd use assert().

> The output of the function must should always be >= 0 as well, but this does not depend on any external factor, so use assert for it (a negative square root is a program bug).
>
> auto sqrt(float val)
> {
>     enfore(val >= 0f);
>
>     float result = ...
>     assert(result >= 0f);
>     return result;
> }

For assert()s about values coming from the caller or returned to it, you can use contracts, to make it clear that you're not only checking an internal invariant of your function:

auto sqrt(float val)
in {
    assert(val >= 0);
}
out(result) {
    if(val == 0)
        assert(result == 0);
    assert(result >= 0);
}
body {
    // use assert()s in the body only for implementation
    // details of your algorithm
    ...
}
February 05, 2016
On Friday, 5 February 2016 at 09:50:43 UTC, Suliman wrote:
> Will asserts stay after compilation in release mode?

No. The only assert that remains in release mode is assert(false) or assert(0) as a way to identify that you've reached a piece of code that shouldn't be executed.
1 2
Next ›   Last »