gabr
gabr

Reputation: 26840

In Delphi, are parameters evaluated in order when passed into a method?

Is the order in which parameters are calculated before a procedure is called defined in Delphi?

IOW, if I have this ugly code (found something like this in a legacy application) ...

function A(var err: integer): integer;
begin
  err := 42;
  Result := 17;
end;

Test(A(err), err);

... is Test guaranteed to receive parameters (17, 42) or could it also be (17, undefined)?


Edit:

Although David's example returns different result with 32-bit and 64-bit compiler, this (luckily) doesn't affect my legacy code because Test(A(err), err) only stores an address of 'err' in the register and it doesn't matter whether the compiler does this before calling A(err) or after.

Upvotes: 15

Views: 1271

Answers (2)

MBo
MBo

Reputation: 80232

Edited: it seems that the compiler may violate the behavior described in the help:

From Calling Conventions help topic (emphasis mine):

The register and pascal conventions pass parameters from left to right; that is, the left most parameter is evaluated and passed first and the rightmost parameter is evaluated and passed last.

Upvotes: 5

David Heffernan
David Heffernan

Reputation: 613252

The order of parameter evaluation in Delphi is not defined.

As an interesting demonstration of this, the following program has different output depending on whether you target 32 or 64 bit code:

program ParameterEvaluationOrder;

{$APPTYPE CONSOLE}

uses
  SysUtils;

function SideEffect(A: Integer): Integer;
begin
  Writeln(A);
  Result := A;
end;

procedure Test(A, B: Integer);
begin
end;

begin
  Test(SideEffect(1), SideEffect(2));
  Readln;
end.

Upvotes: 13

Related Questions