Unexpected behavior when casting away immutable

Mike Parker via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Sep 23 04:58:49 PDT 2015


On Wednesday, 23 September 2015 at 11:38:38 UTC, Mafi wrote:
> On Wednesday, 23 September 2015 at 05:24:05 UTC, John Colvin 
> wrote:
>> On Wednesday, 23 September 2015 at 03:39:02 UTC, Mike Parker 
>> wrote:
> ...
>>>
>>> ```
>>> immutable int x = 10;
>>> int* px = cast(int*)&x;
>>> *px = 9;
>>> writeln(x);
>>> ```
>>>
>>> It prints 10, where I expected 9. This is on Windows. I'm 
>>> curious if anyone knows why it happens.
>>
>> violating immutable is undefined behaviour, so the compiler is 
>> technically speaking free to assume it never happens. At the 
>> very least, neither snippet's result is guaranteed to show a 
>> change or not. At the most, literally anything can happen.
>
> In essence, this code snippet is even better than the OP 
> expected in showing why you shouldn't cast away immutable.

Yes, that's true. I think using both snippets drives the point 
home pretty well.


More information about the Digitalmars-d-learn mailing list