digitalmars.D.learn - cast const pointer to non-const and change value yields neither result
- Timoses (17/17) Apr 30 2018 Hey,
- Stefan Koch (6/23) Apr 30 2018 Well yes.
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?
Apr 30 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.
Apr 30 2018








Stefan Koch <uplink.coder googlemail.com>