Run-time setting of immutable variable?
Steven Schveighoffer
schveiguy at gmail.com
Thu Sep 2 23:12:28 UTC 2021
On 9/2/21 1:17 PM, DLearner wrote:
> I am looking for a mutable Arr but would like an immutable ArrPtr.
Then you want const not immutable.
Here is the reason:
```d
void main()
{
int x = 5;
immutable int *ptr = cast(immutable int *)&x;
assert(*ptr == 5); // ok
x = 6;
assert(*ptr == 5); // what happens here?
}
```
Depending on optimizations and compiler constant folding, that second
assert may pass.
immutable means "I can never change and *everything I point at* can
never change". The compiler is free to use this knowledge to avoid
redoing calculations it has already done. I tknows that `*ptr == 5`
already, and that can never change, so it just doesn't even bother with
the second assert.
However, make ptr *const*, and now not only do you not need the cast,
but the second assert will fail as expected.
> ```
> `Arr` is not immutable, so `ArrPtr` shouldn't point at it if it's
> immutable.
> ```
> Surely there is no inconsistency - at run time the array is in a fixed
> place, so ArrPtr is (or at least should be) a constant, but the
> contents of the array
> can vary as the program runs.
In D, const and immutable are transitive, which means that you can't
have a pointer that is const, but allows changing what it points at. So
while a const pointer *may* work for your purposes, you may want a
specialized type, or a property function. It depends on how you intend
to use `ArrPtr`. Others have given good answers to this problem.
-Steve
More information about the Digitalmars-d-learn
mailing list