Reading about D: few questions

Mafi mafi at
Fri Dec 23 08:31:56 PST 2011

Am 23.12.2011 16:25, schrieb Mr. Anonymous:
> Hi guys!
> I'm mostly familiar with C (and a bit of PHP). I've stumbled upon the D
> language, and I must say I really like it.
> Now I'm reading the "The D Programming Language" book, and I have a
> couple of questions:
> 3. const and immutable.
> Is there any use for const when defining variables?
> As I see it, there is no use for using e.g. const int x;, as it can't be
> modified anyway;
> So with immutable, const is only good for reference variables that are
> initialized to refer to another variable (like a function const ref
> parameter).
> Am I right?
Right. There's no point in a const int but of course there is a big 
difference between const(int)* and immutable(int)*.

> 4. if (&lhs != &rhs)?
> std.algorithm has this in it's swap function.
> Is it different than if (lhs !is rhs)?
> Just wondering.
They're not the same at all. "is" checks if the two operands have binary 
To understand, you have to keep in mind that lhs and rhs are references 
and could refer to one and the same variable as in:
int a = 0; swap(a, a);
Now, if you want to know if two refs refer to the same variable, you
use &lhs == &rhs. If want to know if two class instances are the same, 
you use is. If you want to know if two things (instances or anything 
else) are equal, you use ==.
&lhs == &rhs (makes only sense with refs)
rhs is lhs (always true, if the above is true)
rhs == lhs (always true, if the above is true)

import std.stdio;
void f(ref int[] a, ref int[] b) {
   writefln("%s %s %s", &a == &b, a is b, a == b);

void main() {
   auto u = [1, 2, 3];
   auto u2 = u;
   auto v = [1, 2, 3];
   auto w = [4, 5, 6];
   f(u, u); // true true true
   f(u, u2);// false true true
   f(u, v); // false false true
   f(u, w); // false false false

 > [...]


More information about the Digitalmars-d-learn mailing list