April 30, 2018 cast const pointer to non-const and change value yields neither result nor error | ||||
---|---|---|---|---|
| ||||
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? |
April 30, 2018 Re: cast const pointer to non-const and change value yields neither result nor error | ||||
---|---|---|---|---|
| ||||
Posted in reply to Timoses | 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.
|
Copyright © 1999-2021 by the D Language Foundation