Functional Programming with D

Ali Çehreli acehreli at yahoo.com
Sun Apr 14 08:27:28 PDT 2013


On 04/13/2013 11:35 PM, qznc wrote:

 >> D's immutable is similar to C's const only when we are talking about
 >> values:
 >>
 >>       const int c_i = 42;    // in C immutable d_i = 42;    // in D
 >>
 >> When it is a reference though, not immutable but D's const is similar to
 >> C's const. Otherwise, there is the following difference:
 >>
 >>       // in C: I have no idea whether c is immutable void foo(const 
int *
 >>       c);
 >>
 >>       // in D: I know d is immutable void foo(immutable const ref d);
 >>
 >> (Actually, not only I "know", but I "demand" that d is immutable.)
 >
 > The C variant is an mutable pointer to an immutable int. What is not to
 > know about that?

What foo() does not know is whether the original int is const or not:

     int i = 0;
     foo(&i);

     // Can be mutated by the caller later on
     i = 1;

For that reason, function foo() cannot store the pointer 'c' in 
confidence that it will not change in the future.

Of course you and the dlang.org link that you have provided indicate 
that immutable is not the same as const. When you say "You can qualify 
variables as immutable, which is similiar to C's const and Java's final, 
but it is transitive", it sounds like the main difference that brings 
'immutable' is transitivity but I think the fact that data cannot be 
mutated is the main difference. That makes it possible for a function to 
request immutable data, something not possible in C because a const 
reference parameter is not a requirement but a promise not to mutate.

And of course you never say they are the same; you say "similar". 
Nothing is wrong with that. :)

Ali



More information about the Digitalmars-d-announce mailing list