Assert and undefined behavior

Jesse Phillips Jesse.K.Phillips+D at gmail.com
Sat Oct 14 05:20:47 UTC 2017


On Thursday, 12 October 2017 at 15:37:23 UTC, John Burton wrote:
>
> This is an example of what I mean :-
>
> 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();
> }
>

Yeah the C/C++ community/haters love to talk about all the code 
the compiler can inject because of undefined behavior. But that 
is not what it means.

The compiler does not know the value of data.length so it could 
not make such a transformation of the code. Now had the assert 
been written before the if, you're telling the compiler some 
properties of data.length before you check it and it could make 
such optimizations.

The point is assert tells the compiler something it can use to 
reason about its job, not that it can insert additional runtime 
checks to see if you code is invalid an then add new jumps to 
execute whatever the hell it wants.



More information about the Digitalmars-d-learn mailing list