Assert and undefined behavior

John Burton john.burton at jbmail.com
Thu Oct 12 15:37:23 UTC 2017


On Thursday, 12 October 2017 at 14:22:43 UTC, Timon Gehr wrote:
> On 11.10.2017 11:27, John Burton wrote:

> 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.)
>
> ...
> 
>
> However, in practice, I think none of the current compiler 
> implementations actually uses assert expressions for 
> optimizations.

This is an example of what I mean :-

import std.stdio;

extern void control_nuclear_reactor(int[] data);

void test(int[] data)
{
     if (data.length == 0) {
         writeln("Not enough data!");
     } else {
         control_nuclear_reactor(data);
     }

     assert(data.length > 0);
}

So according to the spec, if data is size zero then the assert 
fails and therefore the code has **undefined behavour**. What 
this means in practice is that the compiler decides that it 
doesn't matter what code is generated for that case as it 
undefined what it is meant to do anyway, so the compiler can 
"optimize" out the if condition as it only affects the case where 
the language doesn't define what it's supposed to do anyway, and 
compiles the code as if it was :-

void test(int[] data)
{
     control_nuclear_reactor();
}

Which obviously could have very bad results if the test mattered.

Yes my program is invalid because I violated it's assumptions but 
I find it very hard to argue that including the assert should 
"break" the code before it.

C++ compilers can and do perform such optimizations so I was 
wondering if assert in D could cause such behavior according to 
the spec.


More information about the Digitalmars-d-learn mailing list