const, final, scope function parameters

Regan Heath regan at netmail.co.nz
Tue May 29 10:56:44 PDT 2007


Robert Fraser Wrote:
> Robert Fraser Wrote:
> > 
> > struct Foo
> > {
> >     int x;
> > }
> > 
> > void bar(in Foo var)
> > {
> >     var.x = 10;
> > }
> > 
> > Allowed?

Assuming 'in' means 'scope, const, final' then "No".  

'const' prevents you modifying the data to which the variable refers.  

In this case that is the contents of the struct. 

In the case of a class reference, the contents of the class to which it refers.  In the case of a pointer, the data to which it points.

You might think that with a value type there is no harm in modifying it because the change is not reflected back to the original variable passed but consider;  

1. What if the programmer wanted that change to be reflected back to the original variable and they have forgotten to use 'ref'?

2. Or, in a large function maintained by more than 1 developer someone changes the input variable and someone else doesn't realise and makes an assumption about it's value, perhaps..

void bar(in Foo var)
{
  assert(var.x == 0);
  //many lines of code
  var.x = 10;
  //many lines of code
  //line which assumes var.x == 0; BANG!
}

> And also, what if it was a reference type instead of a value type:
> 
> class Foo
> {
>     int x;
> }
> 
> void bar(Foo var)
> {
>     var.x = 5; // Is this allowed?
> }

"No", 'const' prevents this too.  It's perhaps more important when reference types are involved because the change will be reflected back to the original variable passed.  Without 'const' someone who wants to call this function cannot guarantee what state their object will be in after the function has finished.  With 'const' you can guarantee the object has not changed.

Regan Heath



More information about the Digitalmars-d mailing list