FOR loops to MAX (LONGINT)

Post Reply
User avatar
Robert
Posts: 1024
Joined: Sat Sep 28, 2013 11:04 am
Location: Edinburgh, Scotland

FOR loops to MAX (LONGINT)

Post by Robert »

I am trying to write a loop that can go up to MAX (LONGINT).
I understand why the simple way to write a FOR loop does not work, so am trying to write a custom WHILE loop.

I noticed that the following code TRAPs; is this a bug?

Code: Select all

  VAR
    a, b  :  LONGINT;
  BEGIN
    a  :=  MAX (LONGINT);
    b  :=  MAX (LONGINT);
    INC (a);
    ASSERT (a = b + 1, 40);
And how do I write a loop that goes from nLow to nHigh where nHigh might be MAX (LONGINT), and might not.
nLow does not need to go to MIN (LONGINT); it will always be positive in my application.
User avatar
Robert
Posts: 1024
Joined: Sat Sep 28, 2013 11:04 am
Location: Edinburgh, Scotland

Re: FOR loops to MAX (LONGINT)

Post by Robert »

This seems to be what I need!

Code: Select all

n  :=  nLo - 1;
WHILE  n  <  nHi  DO
  INC (n);
  ... user code
END;
User avatar
Josef Templ
Posts: 2047
Joined: Tue Sep 17, 2013 6:50 am

Re: FOR loops to MAX (LONGINT)

Post by Josef Templ »

Robert wrote:I am trying to write a loop that can go up to MAX (LONGINT).
I understand why the simple way to write a FOR loop does not work, so am trying to write a custom WHILE loop.

I noticed that the following code TRAPs; is this a bug?
The special situation here is that LONGINT is treated in different ways by the compiler.
INC(a) is compiled into a pair of integer operations (add + add with carry) to form a 64 bit addition
out of two 32-bit operations.
In an expression like "a + 1" the compiler uses the FPU for 64 bit integer operations because, I guess, it uses
less registers and it is also applicable to other operations such as * and DIV.
The observable difference is in the handling of LONGINT overflows, which lead to a TRAP in case of
assigning an overflowed FPU register to an integer variable.

This behavior is described in the docu "Platform-Specific Issues (Windows)" under point 12.

- Josef
User avatar
Robert
Posts: 1024
Joined: Sat Sep 28, 2013 11:04 am
Location: Edinburgh, Scotland

Re: FOR loops to MAX (LONGINT)

Post by Robert »

Josef Templ wrote:This behavior is described in the docu "Platform-Specific Issues (Windows)" under point 12.
Thanks. I agree this is not a bug.
One should not rely on the behaviour of out-of-range arithmetic, even if it is well hidden in

Code: Select all

FOR  n  :=  MAX(LONGINT) - 5  TO  MAX(LONGINT) DO ...
Post Reply