Meaning of const variables

jmh530 via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Jun 20 19:24:03 PDT 2016


I feel like I have a reasonable understanding of when to use 
const as a parameter in a function or for const member functions. 
However, I don't really understand why/when it should be used as 
a type modifier.

For instance, the Programming in D book basically just says 
(http://ddili.org/ders/d.en/const_and_immutable.html) that a 
const variable is the same as an immutable variable, but you 
should just use immutable.

The D spec uses slightly different terminology 
(https://dlang.org/spec/const3.html), I think. I think the 
storage class stuff is similar to what the PiD book says about 
const parameters, while const types further below matches up with 
what the book says about const variables.

So the line from the spec is
"Const types are like immutable types, except that const forms a 
read-only view of data. Other aliases to that same data may 
change it at any time."

I tried making an alias of a const variable and modifying it, but 
that didn't work. So presumably they mean something else. The 
only way I was able to get any kind of meaningful difference is 
that for normal pointers and immutable pointers, I would get 
errors if trying to get the address of non-normal or 
non-immutable variables, respectively. By contrast, I could 
assign an address of any of them (normal, const, immutable) to a 
pointer to a constant variable.

Not sure when I would use this property, or if there are any 
other relevant differences.

void main()
{
	int x1 = 1;
	const(int) x2 = 1;
	immutable(int) x3 = 1;
	
	int* p1_1 = &x1;
	//int* p1_2 = &x2;
	//int* p1_3 = &x3;
	
	const(int)* p2_1 = &x1;
	const(int)* p2_2 = &x2;
	const(int)* p2_3 = &x2;
	
	//immutable(int)* p3_1 = &x1;
	//immutable(int)* p3_2 = &x2;
	immutable(int)* p3_3 = &x3;
	
	p1_1++;
	//p1_2++;
	//p1_3++;
	p2_1++;
	p2_2++;
	p2_3++;
	//p3_1++;
	//p3_2++;
	p3_3++;
}


More information about the Digitalmars-d-learn mailing list