$mathck and Integer2 Expressions

Product Version(s): 3.3x
Operating System:   MS-DOS
Flags: ENDUSER | TAR21809
Last Modified:  4-OCT-1988    ArticleIdent: Q11000

Problem:

Page 61 of the "Microsoft Pascal Reference Manual" describes how
integer2 variables will be changed within a formula to integer4 if the
result will be out of integer2's value range. However, if you use the
metacommand $mathck as described on Page 323, this does not work
correctly. The program will terminate with the error message "out of
integer space."

The following example code demonstrates this problem:

    { changing to INTEGER4 as described in Pascal reference manual }
    { on Page 61 is not done when mathck+ is set }

    { $mathck+ }
    {$line+}
    program p_f01(output);
    VAR L:integer4;
        I1:integer4;
        I: integer;
    begin
    writeln('no error message using only INTEGER4 variables');
    I1:= 1000;
    L:= I1*I1;
    writeln('1000*1000 = ',L);
    writeln;
    writeln('using INTEGER2 variables in expression, result assigned to ');
    writeln('a variable of typ INTEGER4');
    I:=1000;
    L:=I*I;     { will stop with error message right here }
    writeln('1000*1000 = ',l)
    end.

Response:

{$Mathck+} only tells you what the compiler finds. It evaluates the
right-hand side as an integer2 expression, and finds that it cannot
fit the result into an integer2 variable. More explicitly, it
evaluates the right-hand side, determines that I is integer2,
calculates the result, and then determines that the result is not
integer2 and gives you an overflow error.

The conversion of the result to an integer4, which happens if you
delete the {$mathck+} metacommand, occurs at the assignment statement,
not at the calculation of a result. But $mathck keeps a closer eye on
the intermediate results, notes that the results do not fit into a
variable of the type of those variables on the right-hand side, so it
overflows and gives the error, never making it to the assignment that
would have resolved the problem.

To work around this problem, you can multiply the expression on the
right-hand side by an integer4 1. The compiler will then evaluate the
results of the right-hand side as an integer4 rather than integer2 and
so $mathck+ will not give you an error.

The following is an example:

    {$mathck+}
    {$line+}

    program test(output);
    VAR L4, I4, J4:integer4;
                 I:integer ;
    begin
         I4:= 1000;
         L4:= I4*I4;
         J4:= 1;
         writeln('1000*1000 = ',L4);
         I:=1000;
         L4:=J4*I*I;
         writeln('1000*1000 = ',L4)
    end.

This code produces the following results:

1000*1000 =        1000000
1000*1000 =        1000000

Note: you need to place the J4 at the beginning of the right-hand
expression. The statement L4:=I*I*J4; results in the same error. That
is because at the evaluation stage, it will evaluate it according to
the type of the first (left-most) variable that it finds.
