[fpc-pascal] Correct use of var in function calls?

Bo Berglund bo.berglund at gmail.com
Thu Feb 3 22:53:51 CET 2011

I am a bit confused over the way to specify parameters to function
calls as var or not....

I have the following constructs:

  TByteArr = array of byte;

I have a buffer class that receives data from a serial port and now I
want to extract data from this buffer to various types of variables in
the main application class.
So far I have managed all the simple variable types successfully, the
only remaining part is the handling of a body of varying length of
data. In my main class the data will wind up in a dynamic array of
bytes (TByteArr as above).

In the main class:

function xxxx.GetData(Dest:TByteArr): boolean; <== ????
....calculate length of data in bytes as Len....
  SetLength(Dest, Len);
  if not FRxBuf.Read(Dest) then exit;

In the buffer class I have a number of overloaded Read functions:

  function Read(Dest: Pointer; Count: Cardinal): Cardinal; overload;
  function Read(var Data: TByteArr): boolean; overload;
  ... and 5 more....

implemented as:

function TSSCommBuf.Read(var Data: TByteArr): boolean; // <== ???
  Result := Read(@Data, SizeOf(Data)) = SizeOf(Data);

function TSSCommBuf.Read(Dest: Pointer; Count: Cardinal): Cardinal;
  num: Cardinal;
  Src: Pointer;
  num := FWriteIndex - FReadIndex;  //Remaining data bytes in buffer
  if num >= Count then
    num := Count;
  if num > 0 then
    Src := @FBuf[FReadIndex];  // FBuf is a TByteArr sized on demand
    Move(Src^, Dest^, num);
    FReadIndex := FReadIndex + num;
  Result := num;

My question concerns the lines marked with <== ???
Do I use var in the declaration or not? As you can see the similar
functions are differently written now.
In Delphi I think that if an object or a dynamic array is passed as
argument it does not need the var declaration, but I am not sure.
I want to treat the array as a variable because it is the return
container for the data.

Bo Berglund

More information about the fpc-pascal mailing list