Assert and undefined behavior

kdevel kdevel at vogtner.de
Thu Oct 12 20:15:41 UTC 2017


On Thursday, 12 October 2017 at 15:37:23 UTC, John Burton wrote:
> C++ compilers can and do perform such optimizations so I was 
> wondering if assert in D could cause such behavior according to 
> the spec.

In the context of ISO-C++ it is meaningless to reason about the 
"actual behavior" of a non-conforming program ("start WW III" 
etc.). You may find details here: 
<http://en.cppreference.com/w/cpp/language/ub>

As standard oriented C++ (or C or FORTRAN) programmers we avoid 
undefined behavior not because we would want to prevent WW III, 
but because we want to write and reason about conforming code 
only.

IIRC C++'s assert is defined in the ISO-C standard. There we can 
read:

"The assert macro puts diagnostic tests into programs; it expands 
to a void expression. When it is executed, if expression (which 
shall have a scalar type) is false (that is, compares equal to 
0), the assert macro writes information about the particular call 
that failed [...] on the standard error stream in an 
implementation-defined format). It then calls the abort function."

So in C/C++

---
int main ()
{
    assert (0);
    return 0;
}
---

is a perfectly valid (conforming) program.

D ist not standardized (yet) hence there is no such thing as a 
"standard conforming D implementation" or a "standard conforming 
D program". The D documentation is simply the manual of a set of 
programs (compiler, tools) which may or may not be correctly be 
described therin. According to 
<https://dlang.org/spec/contracts.html> the program

---
void main ()
{
    assert (false);
}
---

qualifies as "invalid, and therefore has undefined behaviour." A 
statement, which makes no sense to me. Either it is a "debugging 
aid", that implies defined behavior, or it is undefined behavior, 
then assert (false) cannot aid debugging.


More information about the Digitalmars-d-learn mailing list