Sign in Join

Live chat for Free Pascal, Lazarus, Delphi and every Pascal programmer.

Mailing lists / fpc-devel / 2023-08

Just to confirm, "with" behaviour expected

3 messages · 2 people ·

Reply by email Subscribe to this list Your subscription

Read-only archive. Use j and k to move between messages.

Martin Frb

In the below code, the array is resized (and more important relocated in mem) inside the function "bar".

The commented line (without "with") works as expected.

The "with" line has a different behaviour. I guess it is by design. Just wanted to confirm.

The version with "with" prints 12345 for  "  writeln(a[i,j].x);" For all I can tell the return value of "bar" was written to the old address of that array-entry.

Does "with" take the "address" of the value, and operate on that address, even if the address of that value could change within the "with" statement.

- test was performed with
   fpc 3.2.3  -O1
   fpc 3.3.1  -O4

program Project1;
{$mode objfpc}
procedure outer;
   var
     a: array of array of record x:Integer; end;
     i, j: integer;
   function bar(x: integer): integer;
   begin
     Result := random(99) + 2 * x;
     writeln(Result);
     SetLength(a, 3000, 200);
   end;
   procedure foo;
   begin
     i := random(99);
     j := random(99);
     with a[i,j] do x:= bar(x);
     //a[i,j].x := bar(a[i,j].x);
   end;
begin
   SetLength(a, 100, 100);
   for i := 0 to 99 do
     for j := 0 to 99 do
       a[i,j].x := 12345;
   foo;
   writeln(a[i,j].x);
   readln;
end;
begin
   outer;
end.

Reply by email

Michael Van Canneyt
to Martin Frb
Martin Frb wrote 15 lines
In the below code, the array is resized (and more important relocated in mem) inside the function "bar". The commented line (without "with") works as expected. The "with" line has a different behaviour. I guess it is by design. Just wanted to confirm. The version with "with" prints 12345 for  "  writeln(a[i,j].x);" For all I can tell the return value of "bar" was written to the old address of that array-entry. Does "with" take the "address" of the value, and operate on that address, even if the address of that value could change within the "with" statement.

You may not do this. It is even documented.

See the remark at the end of this page:

https://www.freepascal.org/docs-html/current/ref/refsu62.html#x172-19600013.2.8

Michael.

Reply by email

Martin Frb
to Michael Van Canneyt
Michael Van Canneyt wrote 14 lines
On Mon, 14 Aug 2023, Martin Frb via fpc-devel wrote: > > Does "with" take the "address" of the value, and operate on that > address, even if the address of that value could change within the > "with" statement. You may not do this. It is even documented. See the remark at the end of this page: https://www.freepascal.org/docs-html/current/ref/refsu62.html#x172-19600013.2.8

Ups, sorry I didn't research the details first.

Reply by email