[fpc-devel] Incomplete docs on operator precedence / Question about actual precedence

Sven Barth pascaldragon at googlemail.com
Mon Feb 3 11:48:15 CET 2014


Am 03.02.2014 08:58, schrieb Michael Van Canneyt:
> As for unary minus: this is the same as a binary minus in arithmatic 
> expressions.

Not quite. Take this example:

=== code begin ===

program toppriotest;

{$mode objfpc}
{$modeswitch advancedrecords}

type
   TTest = record
     i: Longint;
     class operator * (aLeft, aRight: TTest): TTest;
     class operator - (aOther: TTest): TTest;
     class operator - (aLeft, aRight: TTest): TTest;
   end;

class operator TTest. * (aLeft, aRight: TTest): TTest;
begin
   Writeln(aLeft.i, ' * ', aRight.i);
   Result.i := aLeft.i * aRight.i;
end;

class operator TTest. - (aOther: TTest): TTest;
begin
   Writeln('- ', aOther.i);
   Result.i := - aOther.i;
end;

class operator TTest. - (aLeft, aRight: TTest): TTest;
begin
   Writeln(aLeft.i, ' - ', aRight.i);
   Result.i := aLeft.i - aRight.i;
end;

var
   t1, t2: TTest;
begin
   t1.i := 42;
   t2.i := 21;
   Writeln((-t1).i);
   Writeln((t1 * t2).i);
   Writeln((t1 - t2).i);
   Writeln((t1 * -t2).i);
   Writeln((-t1 * t2).i);
   Writeln((t1 - t2 * -t1).i);
   Writeln((t1 - -t2).i);
   Readln;
end.

=== code end ===

Will result in this output:

=== output begin ===

- 42
-42
42 * 21
882
42 - 21
21
- 21
42 * -21
-882
- 42
-42 * 21
-882
- 42
21 * -42
42 - -882
924
- 21
42 - -21
63

=== output end ===

So unary minus (and also unary plus which is a valid operator as well!) 
binds stronger than multiplication.

Regards,
Sven



More information about the fpc-devel mailing list