
{: test that sqr(n) causes a fatal error if it overflows }

{$d+}
program d021( output );

var
   k, l, h : 0..maxint;
function side : integer;
begin
   side := k;
   k := k+1;
end;
begin {d021}
   k := 1;
   while sqr(k) <= maxint div 4 do
      k := 2*k;

   h := 2*k+1;
   l := k;
   {sqr(l) <= maxint, sqr(h) > maxint}

   while h > l+1 do begin
      k := (h-l) div 2;
      if sqr(l) > maxint -sqr(k) - 2*l*k then
         h := l+k
      else
         l := l+k;
   end;

   { now, sqr(l) <= maxint, sqr(l+1) > maxint }

   k := l;
   writeln( 'sqr(', -k:1, ') is ', sqr(-side):1 ); { this should not overflow }
   if k <> 1+l then
      writeln( 'side effect error evaluating sqr' );
   k := l+1;
   writeln( 'sqr(', -k:1, ') is ', sqr(-k):1 ); { this should overflow }
end. { d021 }

