[fpc-pascal] const parameter writeable

Michael Müller mueller_michael at nikocity.de
Mon May 1 08:11:13 CEST 2006


On Sat, Apr 29, 2006 at 11:20:04PM +0200, Peter Vreman <peter at freepascal.org> wrote:
> >
> > Are const parameters supposed to ensure read only access?
> > If so how come one can write to a typed pointer?
> >
> > program project1;
> >
> > {$mode objfpc}{$H+}
> >
> >   type
> >     PSomeRec = ^TSomeRec;
> >     TSomeRec = record
> >       a: string;
> >       b: string;
> >     end;
> >
> >   procedure ChangeRec1(const Rec: PSomeRec);
> >   begin
> >     Rec^.a:= 'string A';
> >   end;
> >
> > var
> >   RecPtr: PSomeRec;
> > begin
> >   new(RecPtr);
> >   ChangeRec1(RecPtr);
> >   writeln(RecPtr^.a);
> >   dispose(RecPtr);
> >   readln;
> > end.
> 
> Only the pointer itself is the parameter and read-only. Where the pointer
> points to is irrelevant.

But in this case I'm wondering why you want to give a pointer instead
of the real type?

The reason for a pointer is normally in this case to avoid that the
given data is copied into local variables.

>From my understand the compiler handles following parameter attributes:
- 'var': call by reference => gives pointers, content writable
- 'const': gives pointer, content read-only
- '': call by value => creates a local copy of the data, content is
lost after end of procedure/function
- 'out': I'm not sure if it's more similar to 'var' or ''.

This is the reason why I always declare parameters that are not 'var'
with 'const'.

Are my expanations right especially related to 'const'?

Michael



More information about the fpc-pascal mailing list