Recent

Author Topic: [SOLVED] functions with same return record-type share a record(?)  (Read 5530 times)

ASerge

  • Hero Member
  • *****
  • Posts: 2337
Re: functions with same return record-type share a record(?)
« Reply #30 on: May 20, 2024, 04:06:25 am »
My vision of the situation:
Case 1: with "if dword(@result) = 0 then".
Case 2: without.

In the first case, the compiler does everything right:
1. Initialize temp variable for Result before call B with nil.
2. Do Result.bar := 'foo';
3. Initialize temp variable for Result before call A with nil.
4. Call A (Result equal ' bar').
and so on.

In the second case, compiler decides to optimize, and does not do step 3, but simply reuses the same register.
The result is unexpected behavior ('foo bar').

Step 3 is almost always used by the compiler to avoid side effects, for example, when Result := Format('...%s...', [...Result...]) is called.
As you can see, with some types of optimization, it forgets this.

WooBean

  • Sr. Member
  • ****
  • Posts: 277
Re: functions with same return record-type share a record(?)
« Reply #31 on: May 20, 2024, 07:40:35 am »
Are there only "function" fans?

What does stop you from using "procedure"?

Code: Pascal  [Select][+][-]
  1. program Project1;
  2. {$mode objFPC}
  3. uses sysutils;
  4. type
  5.   TRecord = record
  6.     a:string;
  7.     id:integer;
  8.   end;
  9. procedure OperateOnTheRecord(var rec: TRecord; param:string);
  10. begin
  11.   inc(rec.id);
  12.   if odd(rec.id) then
  13.     rec.a:=rec.id.ToString+'. '+rec.a+lowercase(param)
  14.   else
  15.     rec.a:=rec.id.ToString+'  '+rec.a+uppercase(param);
  16. end;
  17.  
  18. var b:TRecord;
  19.     i:integer;
  20. begin
  21.   b:=default(TRecord);
  22.  
  23.   for i:=1 to 10 do begin
  24.     OperateOnTheRecord(b,'Abc');
  25.     writeln(b.a);
  26.   end;
  27.   readln;
  28. end.
  29.  



« Last Edit: May 20, 2024, 03:57:51 pm by WooBean »
Platforms: Win7/64, Linux Mint Ulyssa/64

ASerge

  • Hero Member
  • *****
  • Posts: 2337
Re: functions with same return record-type share a record(?)
« Reply #32 on: May 20, 2024, 05:59:56 pm »
What does stop you from using "procedure"?
I agree. If need to use the value specified before the call, then need to use a procedure with a parameter, not a function in a non-standard way.

PascalDragon

  • Hero Member
  • *****
  • Posts: 5759
  • Compiler Developer
Re: functions with same return record-type share a record(?)
« Reply #33 on: May 22, 2024, 09:51:10 pm »
So you say if im inside function func1 I can append something to .bar? And I can be 100% sure the "foo" string will be already there in .bar?

This is an implementation detail and might work in most cases, but especially depending on optimizations and temporary variables involved this behavior might change.

So do not rely on it or you will be bitten some time in the future. If you want to modify something then pass it as var-parameter.

 

TinyPortal © 2005-2018