D defined behavior

kinke noone at nowhere.com
Mon Apr 27 15:13:46 UTC 2020


On Monday, 27 April 2020 at 14:07:49 UTC, Luís Marques wrote:
> I've lost track. Does D have undefined behavior at all? (e.g. 
> outside @safe code).
>
> In any case, I imagine that the D spec (ha!) would dictate that 
> the following code should print 0x10001, although that's not 
> quite clear.
>
> GDC (optimized) prints 0x1.
> LDC2 prints 0x10001, but I suspect only because LLVM doesn't 
> happen to do the same optimization, not because this is handled 
> properly.
>
> ```
> import std.stdio;
>
> @safe:
>
> int foo(int* a, int* b) {
>     *a = 1;
>     *b = 1;
>     return *a;
> }
>
> void main() {
>     ubyte[6] buffer;
>     auto a = cast(int[]) (buffer[0 .. 4]);
>     auto b = cast(int[]) (buffer[2 .. 6]);
>     writefln("0x%X", foo(&a[0], &b[0]));
> }
> ```

A case where LDC goes further than GDC, wrt. infinite loops (see 
https://github.com/ldc-developers/ldc/issues/2827):

void foo() @safe
{
     int x;
     while (x != x + 1)
         ++x;
}

int bar(int p) @safe
{
     if (p > 1)
         foo();
     return p;
}

With -O, LDC optimizes bar() to simply returning p. See 
https://godbolt.org/z/84wZ9k.


More information about the Digitalmars-d mailing list