15.5 Comparison operator

The comparison operator can be overloaded to compare two different types or to compare two equal types that are not basic types. If the operands are not simple types, the result type of a comparison operator need not always be a boolean, but then they cannot be used in an if, repeat or while statement.

The comparison operators that can be overloaded are:

equal to
(=) To determine if two variables are equal.
unequal to
(<>) To determine if two variables are different.
less than
(<) To determine if one variable is less than another.
greater than
(>) To determine if one variable is greater than another.
greater than or equal to
(>=) To determine if one variable is greater than or equal to another.
less than or equal to
(<=) To determine if one variable is greater than or equal to another.

If there is no separate operator for unequal to (<>), then, to evaluate a statement that contains the unequal to operator, the compiler uses the equal to operator (=), and negates the result. The opposite is not true: if no “equal to” but an “unequal to” operator exists, the compiler will not use it to evaluate an expression containing the equal (=) operator.

As an example, the following operator allows to compare two complex numbers:

operator = (z1, z2 : complex) b : boolean;

the above definition allows comparisons of the following form:

Var  
  C1,C2 : Complex;  
 
begin  
  If C1=C2 then  
    Writeln(’C1 and C2 are equal’);  
end;

The comparison operator definition needs two parameters, with the types that the operator is meant to compare. Here also, the compiler doesn’t apply commutativity: if the two types are different, then it is necessary to define two comparison operators.

In the case of complex numbers, it is, for instance necessary to define 2 comparisons: one with the complex type first, and one with the real type first.

Given the definitions

operator = (z1 : complex;r : real) b : boolean;  
operator = (r : real; z1 : complex) b : boolean;

the following two comparisons are possible:

Var  
  R,S : Real;  
  C : Complex;  
 
begin  
  If (C=R) or (S=C) then  
   Writeln (’Ok’);  
end;

Note that the order of the real and complex type in the two comparisons is reversed.

The following example shows that the result type does not need to be a boolean:

Type  
  TMyRec = record a,b : integer; end;  
 
operator = (x,y : TMyRec) r : string;  
 
begin  
  if (x.a=y.a) and (x.b=y.b) then  
    R:=’equal’  
  else  
    R:=’differ’;  
end;  
 
var  
  x,y : TMyRec;  
 
begin  
  x.a:=1;  
  y.a:=1;  
  Writeln(x=y);  
  x.a:=2;  
  y.a:=3;  
  Writeln(x=y);  
end.

When executed, this example will print

equal  
differ

obviously, a statement as

if (x=y) then  
  writeln(’Equal’);

Will not compile, since the if statement needs a boolean check:

Error: Incompatible types: got "ShortString" expected "Boolean"