[fpc-pascal] const parameter writeable

L505 fpc505 at z505.com
Tue May 2 18:51:59 CEST 2006


> > >
> > > But in this case I'm wondering why you want to give a pointer instead
> > > of the real type?
> >
> >
> > did you mean this ? :
> >
> >    procedure ChangeRec1(const Rec: TSomeRec);
> >    begin
> >      Rec.a:= 'string A';
> >    end;
>
> Yes.

Well, this is a Precord. That doesn't work. That is why I was confused.

>
> > Because I can't pass a PSomeRec to that function, only a TSomeRec
>
> Where is the problem? If you allocated the memory by new() as in your
> example you could call
> ChangeRec1(RecPtr^);
> and the compile (hopefully) uses the pointer.

Yes, but you are repeating what Jonas says - if you would have told me this first, you
would have gotten the brownie points. But Jonas gets them. :-)

>
> But in this case you will get an compiler error because you can't
> change a constant value.
>
> It seemed that I didn't get the point from your original mail:
> Name the procedure CHANGERec1 and change a value but declare the
> parameter as constant.

I was asking why I could write to a const. But in fact I was not writing to the CONST, I
was actually writing to the const data it pointed to.  With SomeRec^ I cannot write to
const. Problem solved.

I was using sloppy Delphi style code without ^ since Delphi enforces this sloppy style of
coding, and now I know why not to use sloppy delphi style code. 

What I was confused about was why you recommended TSomeRec when we are dealing with
PSomeRec.

I also stated that I knew you can pass TSomeClass as a const, you can still access it's
properties even though it is a const.

 program project1;

 {$mode objfpc}{$H+}

   type
     TSomeClass = class
       a: string;
       b: string;
     end;

   procedure ChangeClass(const SomeClass: TSomeClass);
   begin
     SomeClass.a:= 'string A';
   end;

 var
   SomeClass: TSomeClass;
 begin
   someclass:= TSomeClass.create;
   ChangeClass(someclass);
   writeln(someclass.a);
   someclass.free;
   readln;
 end.

This is normal, because we are passing a pointer when dealing with a class - not passing
the class contents. Which is really what I should have thought about before asking the
question, because I have discovered you can write to a const class *contents* before. 




More information about the fpc-pascal mailing list