### Bookstore

 Computer Math and Games in Pascal (preview) Lazarus Handbook

### Recent

#### avk

• Sr. Member
• Posts: 325
##### Advanced records as function parameters
« on: September 30, 2020, 06:53:20 pm »
Hi!

A simple test
Code: Pascal  [Select][+][-]
2. {\$mode objfpc}{\$H+}
4. uses
5.   SysUtils;
6. type
7.   TIntArray = array of Integer;
8.   TTest = record
9.     Data: TIntArray;
10.     function IsSame(const aRec: TTest): Boolean;
11.     function IsSame2(constref aRec: TTest): Boolean;
12.   end;
13.
14. function TTest.IsSame(const aRec: TTest): Boolean;
15. begin
16.   WriteLn('IsSame:');
17.   WriteLn('@aRec = ', Format('\$%p', [@aRec]));
18.   WriteLn('@Self = ', Format('\$%p', [@Self]));
19.   if @aRec = @Self then
20.     exit(True);
21.   Result := False;
22. end;
23.
24. function TTest.IsSame2(constref aRec: TTest): Boolean;
25. begin
26.   WriteLn('IsSame2:');
27.   WriteLn('@aRec = ', Format('\$%p', [@aRec]));
28.   WriteLn('@Self = ', Format('\$%p', [@Self]));
29.   if @aRec = @Self then
30.     exit(True);
31.   Result := False;
32. end;
33.
34. var
35.   t: TTest;
36.
37. begin
38.   t.Data := [1, 2, 3, 4];
39.   WriteLn(t.IsSame(t));
40.   WriteLn(t.IsSame2(t));
41. end.
42.
gives an interesting result for i386_win-32(fpc-3.3.1r46955):
Code: Text  [Select][+][-]
1. IsSame:
2. @aRec = \$0141FF48
3. @Self = \$00419010
4. FALSE
5. IsSame2:
6. @aRec = \$00419010
7. @Self = \$00419010
8. TRUE
9.

What am I missing?
« Last Edit: September 30, 2020, 07:03:38 pm by avk »

#### Martin_fr

• Hero Member
• Posts: 6716
• Debugger - SynEdit - and more
##### Re: Advanced records as function parameters
« Reply #1 on: September 30, 2020, 07:10:42 pm »
If you pass a record (advanced or not) as parameter, then this is passing the actual data => you hand over a copy.

Records (unlike classes) are not passed by reference.
Though apparently advanced record in "self" is passed by ref (and needs to be => it is a "var param")

"const arec: TTEst"
allows the compiler to choose between copy or ref. Apparently for the specific record a copy was passed.

"constref" forces a ref. (same as "var param")

#### WooBean

• Jr. Member
• Posts: 92
##### Re: Advanced records as function parameters
« Reply #2 on: September 30, 2020, 07:13:04 pm »
I think the answer is here: https://www.freepascal.org/docs-html/ref/refsu66.html

It is not limited to advanced records or a particular target platform.

WB
Win7/64, Lazarus 1.8 win64-win64, FPC 3.0.4

#### avk

• Sr. Member
• Posts: 325
##### Re: Advanced records as function parameters
« Reply #3 on: September 30, 2020, 08:27:10 pm »
Thanks to everyone who answered, the question was pretty silly. Hence the simple conclusion: at night a person should sleep.