CTFE limitation on reinterpreting cast

Rambutan s56l6zk0w at mozmail.com
Wed Sep 30 03:38:02 UTC 2026


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.



More information about the Digitalmars-d mailing list