11 hours ago

Re: CTFE limitation on reinterpreting cast
Gravatar of Walter BrightPosted by Walter Bright
in reply to Rambutan
PermalinkReply
Gravatar of Walter Bright

Posted in reply to Rambutan

On 9/28/2026 3:50 PM, Rambutan wrote:
> struct B {}
> struct C {}
> 
> __gshared B Bobj;
> 
> auto ptr = cast(C*)&Bobj;

CTFE does not do anything that is not memory safe. Consider:

```d
struct B { int b; }
struct C { long c; }

__gshared B Bobj;

auto ptr = cast(C*)&Bobj;
```

This fails, because the structs are laid out differently, and `ptr.c` will produce memory unsafe behavior.

You could make the point that if the layouts of B and C are identical, this would be memory safe and should work.

Feel free to make the case for it!

8 hours ago

Re: CTFE limitation on reinterpreting cast
Gravatar of RambutanPosted by Rambutan
in reply to Walter Bright
PermalinkReply

Rambutan

Gravatar of Rambutan

Posted in reply to Walter Bright

On Wednesday, 30 September 2026 at 00:17:25 UTC, Walter Bright wrote:
> On 9/28/2026 3:50 PM, Rambutan wrote:
>> struct B {}
>> struct C {}
>> 
>> __gshared B Bobj;
>> 
>> auto ptr = cast(C*)&Bobj;
>
> CTFE does not do anything that is not memory safe. Consider:
>
> ```d
> struct B { int b; }
> struct C { long c; }
>
> __gshared B Bobj;
>
> auto ptr = cast(C*)&Bobj;
> ```

Thank you for confirming what I speculated earlier in this thread when I said this is dangerous and so may be the motive for banning reinterpreting casts in CTFE.

However I also pointed out that there is no problem with such a cast if the new pointer is never indirected in any way at compile time. So a better rule would be to ban any kind of indirection using the result of a reinterpreting cast, and NOT to ban the cast itself.

That way placing cast pointers to globals in global struct initializers would be legal, as it is in C.