cast const pointer to non-const and change value yields neither result nor error

Stefan Koch uplink.coder at googlemail.com
Mon Apr 30 12:41:06 UTC 2018


On Monday, 30 April 2018 at 12:35:06 UTC, Timoses wrote:
> Hey,
>
> reading through https://dlang.org/articles/const-faq.html and 
> experimenting a bit:
>
> ```
>     immutable int i = 3;
>     const(int)* p = &i;
>
>     int* q = cast(int*)p;
>
>     assert(q == p && p == &i);
>
>     writeln(i); // 3
>     *q = 1;     // Why does this have no effect at all? No 
> error no nothing?!
>     writeln(i); // 3
> ```
>
> When changing i to non-immutable the `*q=1` sets i to 1.
>
> There is no error message. The `*q=1` simply has no effect at 
> all. Also with `const int i`.
>
> Is that intended?

Well yes.
Casting away immutable is undefined behavior.

This code will most probably not compile if you annotate it with 
@safe.
Precisely because it's undefined.



More information about the Digitalmars-d-learn mailing list