Unexpected behavior when casting away immutable

Mike Parker via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Sep 22 20:39:01 PDT 2015


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.


More information about the Digitalmars-d-learn mailing list