[swift-evolution] Asserts should not cause undefined behaviour

Chris Lattner clattner at apple.com
Thu Dec 31 14:27:01 CST 2015

On Dec 28, 2015, at 5:48 AM, Joseph Lord via swift-evolution <swift-evolution at swift.org> wrote:
> The documented behaviour of assert and assertionFailure in "disable safety checks" builds (still documented as -Ounchecked) is that the compiler "may assume that it would evaluate to true" or in the assertionFailure case never be called.


> This documented behaviour would allow the compiler to completely eliminate tests and branches before or after the assertion and take the operation deep into undefined behaviour.

Only in cases where the assertion would have failed, right?  The point of -Ounchecked is that - if your code was correct with the checks - that it will still be correct.  Disabling overflow and array bounds checks is far more dangerous than the assertion behavior you cite here.

> It appears from the code as if the assumption is not currently applied on the assert method although it is on the assertionFailure case by means of the _conditionallyUnreachable() call. assert seems to be a no-op in both normal release and disable safety checks build modes.


> [Proposed Change]
> Change the documentation for assert and assertionFailure so that behaviour in unchecked mode is the same as in normal release - no evaluation and no effect.

Why? :

> 1) Expected behaviour based on other languages is for assert to have no effect in release. (If current behaviour is highly desired another function name should be used). Having potential dangerous behaviour from a function that is familiar across languages and is regarded as a safety feature is undesirable.

This is the C model, but as you know, there is a whole field of custom assertions libraries that people have developed.  I don’t think there is anything like consensus on this topic.

> 2) Adding asserts to code should not make the code more dangerous whatever the build. Assuming the truth of the assert may lead to runtime safety checks being skipped and undefined behaviour when a no-op would be a safe behaviour.

This only affects code built with -Ounchecked, which is definitely not a safe mode to build your code.  The intention of this mode is that you can use it to get a performance boost, if you believe your code to be sufficiently tested.  This mode, which isn’t the default in any way, intentionally takes the guard rails off to get better performance.

If you don’t like that model, don’t use this mode.

> 3) "For highly robust code assert and then handle the error anyway" [Code Complete 2nd Edition section 8.2]

Highly robust code shouldn’t build with -Ounchecked, so I don’t see how this point is pertinent.


More information about the swift-evolution mailing list