Search code examples
pascaloperator-precedence

Linear equation, incompatible types BOOLEAN/LONGINT


I've got exercise about linear equation in Pascal and I've created simple code for comparison input numbers but when I try to run it. I have problem about incompatible types, got BOOLEAN and expected LONGINT.

program LinearEquation;

var
  a, b: real;

begin
  readln(a, b);

  if (b = 0 and a = 0) then
    writeln('INFINITY')
  else if (b = 0 and a <> 0) then
    writeln(1)
  else if (a = 0 and b <> 0) then
    writeln(0)
  else if(b mod a = 0) then
    writeln(1);

  readln;

end.

and

13 / 9 rownan~1.pas
 Error: Incompatible types: got "BOOLEAN" expected "LONGINT"
15 / 14 rownan~1.pas
 Error: Incompatible types: got "BOOLEAN" expected "LONGINT"
17 / 14 rownan~1.pas
 Error: Incompatible types: got "BOOLEAN" expected "LONGINT"
17 / 14 rownan~1.pas
 Error: Incompatible types: got "BOOLEAN" expected "LONGINT"

Solution

  • At least in modern Delphi, and has higher precedence than =, so

    a = 0 and b = 0
    

    is interpreted as

    (a = (0 and b)) = 0.
    

    But the and operator cannot accept an integer and a floating-point value as operands (two integers would have been OK, though). Hence the error.

    Had a and b been integers, 0 and b would have been the bitwise conjunction of 0 and b, that is, 0. Thus, we would have had

    (a = 0) = 0.
    

    This reads either true = 0 (if a is equal to 0) or false = 0 (if a is different from 0). But a boolean cannot be compared to an integer, so the compiler would have complained about that.

    Still, this was just an academic exercise. Clearly, your intension was

    (a = 0) and (b = 0).
    

    Just add the parentheses:

    if (b = 0) and (a = 0) then
      writeln('INFINITY')