Unexpected behavior when casting away immutable

John Colvin via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Sep 22 22:24:03 PDT 2015


On Wednesday, 23 September 2015 at 03:39:02 UTC, Mike Parker 
wrote:
> I have a situation where I would like to demonstrate violating 
> the contract of immutable (as an example of what not to do), 
> but do so without using structs or classes, just basic types 
> and pointers. The following snippet works as I would expect:
>
> ```
> immutable int i = 10;
> immutable(int*) pi = &i;
> int** ppi = cast(int**)π
> writeln(*ppi);
> int j = 9;
> *ppi = &j;
> writeln(*ppi);
> ```
>
> Two different addresses are printed, so I've successfully 
> violated the contract of immutable and changed the value of pi, 
> an immutable pointer. However, this does not work as I expect.
>
> ```
> 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.


More information about the Digitalmars-d-learn mailing list