Confused about const

Pelle Månsson pelle.mansson at
Sat Mar 20 07:24:59 PDT 2010

On 03/20/2010 01:58 AM, Paul D. Anderson wrote:
> I created a struct, call it "S", and some functions that operate on S. But I'm confused about when const is useful.
> Being an old Java programmer, I use 'const' the same as I used 'final' in Java. So most of my functions look like this:
> S for(const S a, const S b) {
>      S x = a;
>      S y = b;
>      // do some stuff
>      return a;
> }
> I declare the parameters const and then copy them to work on them.
> I get error messages about not implicitly casting const S to S. So I can make an explicit cast:
>      S x = cast(S) a;
>      S y = cast(S) b;
> and the error messages go away.
> But I think I must have gone off the rails somewhere -- all I want is for the caller to be sure the function doesn't alter a and b. But I end up with lots of casts to/from const. What am I missing??
> Paul

I think you misunderstand const. If you flag an argument with const it 
means you're unable to ever change anything reachable from that 
argument, so if you have a const reference, you can not alter anything 
reachable from that reference.

If you have this:

struct S {
     int[] xs;
S foo(const S s) {
     return cast(S)s;
void main() {
     S s;
     s.xs = [1,4,5];
     S fromconst = foo(s);
     fromconst.xs[0] = 4; //<-- there you alter something you
                          // should not be able to alter.

The compiler protects you from this, unless you cast your constness away.

If you want to copy, you'll need to implement the proper deep copying 
yourself. :)

More information about the Digitalmars-d-learn mailing list