Run-time setting of immutable variable?

jfondren julian.fondren at gmail.com
Thu Sep 2 17:34:18 UTC 2021


On Thursday, 2 September 2021 at 17:17:15 UTC, DLearner wrote:
> 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 the case of `immutable(T)* ArrPtr`, the contents of the 
pointed-to array cannot vary as the program runs. If it's 
immutable, nothing in the program ever mutates it. In the case of 
`const(T)* ArrPtr`, the contents of the pointed-to array can vary 
as the program runs, and the only restriction is that the array 
can't be mutated through ArrPtr.

If what you mean is that you want the *pointer* to never change, 
`T * const ArrPtr` in C syntax, but that you don't care if the 
pointed-to array changes via ArrPtr or any other reference, then 
I don't think D can express this. You could make ArrPtr a 
function:

```d
void main() {
     int[] xs = [1, 2, 3, 4];
     int* p() { return &xs[2]; }
     p[0] = 0;
     assert(xs == [1, 2, 0, 4]);
     p++; // Error: ... not an lvalue and cannot be modified
}
```


More information about the Digitalmars-d-learn mailing list