[fpc-pascal] Strange "division by zero" error using variants

Michalis Kamburelis michalis.kambi at gmail.com
Tue May 24 23:01:12 CEST 2022


That's a funny interaction between Variants and Pascal's ambiguous
(logical or bitwise) "and" :) Both the operators and the types are
ambiguous -> making the boolean short-circuit evaluation not possible.

Indeed one workaround is to cast the variants to Booleans explicitly,
which makes it use logical "and" with expected result. I.e. this
doesn't raise "division by zero":

if Boolean(v1) and Boolean(v2 > 0) and Boolean((0+1) mod v2 = 0) then
Writeln ('ok');

Regards,
Michalis

wt., 24 maj 2022 o 22:52 Florian Klämpfl via fpc-pascal
<fpc-pascal at lists.freepascal.org> napisał(a):
>
> Am 24.05.22 um 19:28 schrieb Thomas Kurz via fpc-pascal:
> > Dear all,
> >
> > please consider the following code:
> >
> >
> > program Project1;
> >
> > {$booleval off}
> >
> > var
> >    v1, v2: variant;
> >    a: boolean;
> >    b: integer;
> >
> > begin
> >    a := true;
> >    b := 0;
> >    // this works as expected:
> >    if a and (b > 0) and ((0+1) mod b = 0) then Writeln ('ok');
> >
> >    v1 := true;
> >    v2 := 0;
> >    // this gives a "division by zero":
> >    if v1 and (v2 > 0) and ((0+1) mod v2 = 0) then Writeln ('ok');
> > end.
> >
> >
> > The "variant" variant results in a "division by zero". Obviously, it tries to evaluate the modulo-expression even though this shouldn't happen because complete boolean evaluation is disabled and the "if"-result is already known to be false after checking "v2>0".
> >
> > Can anyone explain this strange behavior?
>
> When compiling the and expressions, the compiler does not know (in this
> example it could, but in general it cannot) what the variants contain so
> just the variant and-operator is executed which does not/cannot
> distinguish between the logical and bitwise and variant.
> _______________________________________________
> fpc-pascal maillist  -  fpc-pascal at lists.freepascal.org
> https://lists.freepascal.org/cgi-bin/mailman/listinfo/fpc-pascal


More information about the fpc-pascal mailing list