Assert and undefined behavior

Timon Gehr timon.gehr at gmx.ch
Thu Oct 12 14:22:43 UTC 2017


On 11.10.2017 11:27, John Burton wrote:
> The spec says this :-
> 
> "As a contract, an assert represents a guarantee that the code must 
> uphold. Any failure of this expression represents a logic error in the 
> code that must be fixed in the source code. A program for which the 
> assert contract is false is, by definition, invalid, and therefore has 
> undefined behaviour."
> 
> Now I worry about the words "undefined behavior" because in C++ compiler 
> writers seem to have decided that these words mean that it's ok for the 
> compiler to generate code to do whatever it feels like even in 
> unconnected code and even before the undefined behavior is invoked 
> because some subsequent code has undefined behavior.
> 
> From my C++ experience this paragraph tells me that if I use "assert" 
> to check my assumptions, and the assertion is false, then this could 
> lead to my program failing in unpredictable ways unconnected with the 
> actual assertion.
> 

Yes, that's what it is saying. (The other answers, that say or try to 
imply that this is not true or true but not a bad thing, are wrong.)

To make this more obvious, see:

http://forum.dlang.org/post/lrbpvj$mih$1@digitalmars.com

Refer to point 2. The fix is to not use both assert and -release.

However, in practice, I think none of the current compiler 
implementations actually uses assert expressions for optimizations.


More information about the Digitalmars-d-learn mailing list