Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

delphi

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.

like image 293
gabr Avatar asked Jun 13 '12 07:06

gabr


People also ask

Does order matter for parameters?

An example would be ADD : ADD(1,2) and ADD(2,1) can be used interchangeably, the order of parameters does not matter.

What is a parameter Delphi?

Parameters are special kind of variables declared in a subroutine that are used to input some value into that subroutine. And the values that we pass in a function call is called as Arguments. in Delphi we can declare functions/procedures with parameters like following. Example of a Function declaration.

How do you pass by reference in Delphi?

In Delphi to pass by reference you explicitly add the var keyword: procedure myFunc(var mytext:String); This means that myFunc can modify the contents of the string and have the caller see the changes.

What is procedure in Delphi?

In Delphi, there are generally two types of subroutines: a ​function and a procedure. The usual difference between a function and a procedure is that a function can return a value, and a procedure generally will not do so. A function is normally called as a part of an expression.


1 Answers

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.
like image 73
David Heffernan Avatar answered Sep 28 '22 11:09

David Heffernan