Meaning of const variables

Mike Parker via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Jun 21 00:17:03 PDT 2016


On Tuesday, 21 June 2016 at 02:24:03 UTC, jmh530 wrote:

> I tried making an alias of a const variable and modifying it, 
> but that didn't work. So presumably they mean something else.

By alias they mean another reference (or view) to the data, as in 
Ketmar's example and your assignment of a &x1 to p2_1. No one can 
modify the value of x1 through p2_1 because it's const, but it's 
still possible to modify x1 directly. This is most obvious with 
reference types like pointers, classes and arrays. In this case, 
it's possible for the data and the view to the data to be 
separate.

int x;          // The data (and one view to it)
int *px = &x;   // A second view to the same data

For value types, there's effectively no difference between const 
and immutable, because a value type is both a view to the data 
*and* the data itself. If it is const or immutable, it's 
impossible to have any mutable view to the same data e.g.:

const cx = 1;
immutable ix = 2;

int* pcx = &cx;  // No Can do
int* pix = &ix;  // Ditto

In this case, you might as well go with immutable, since the 
behavior is identical. And really, if you never need to take the 
address of the variable, then a manifest constant using enum 
would be more appropriate.

The same holds true for any reference types that you can 
initialize with only one view, such as an array or a class 
(though you wouldn't want to use a manifest constant with these 
most of the time).

const(int)[] ints1 = [0, 1, 2, 3, 4];
const(int[]) ints2[0, 1, 2, 3, 4];

In both of these cases, the original view of the data (the array 
literal) is temporary. You can't change the values at any index 
in these arrays once they are initialized because it is not 
possible to take a mutable view of the data. May as well go ahead 
and use immutable here.

I think that's what Ali was getting at in PiD. IIRC, I said the 
same thing in Learning D.




More information about the Digitalmars-d-learn mailing list