Range checking not working as expected?



Hello,

Consider this:

with Ada.Text_IO, Ada.Integer_Text_IO;
procedure Overflow is
   A : Integer := 0;
   D : constant Integer := 500000000;
begin
   for I in 1..20 loop
      Ada.Integer_Text_IO.Put(A);
      Ada.Text_IO.New_Line;
      A := A + D;
   end loop;
end Overflow;

On my machine (PC+Linux+GNAT) it produces the following output:

          0
  500000000
 1000000000
 1500000000
 2000000000
-1794967296
-1294967296
 -794967296
 -294967296
  205032704
  705032704
 1205032704
 1705032704
-2089934592
-1589934592
-1089934592
 -589934592
  -89934592
  410065408
  910065408

Not good - I expected constraint error instead of going round the counter.
What has really confused me is that declaring A as Natural gives the same effect.
Further investigation with the following declarations:


   type MyType is range 0..Integer'Last;
   A : MyType := 0;

(and type casts later, when necessary)

showed exactly the same effect. Following this path, I tried this:

   type MyType is range 0..Integer'Last - 1;
   A : MyType := 0;

And *now* I got what I wanted - the constraint error.

What's going on? Well, I understand the low-level mechanics of this difference (and also why this might be a border-case for the compiler), but the question is rather high-level: what does *that* mean? :)


-- Maciej Sobczak : http://www.msobczak.com/ Programming : http://www.msobczak.com/prog/ .



Relevant Pages

  • Re: Newbie trying to cleanup/format text file
    ... Using a constant integer with the range operator in a while loop is a ... execution back to the beginning of the loop. ...
    (perl.beginners)
  • Re: LOCALISATION
    ... In case the loop is not executed at all. ... To make the value of the CV visible to the exception handler. ... Why not PL/I, I wonder. ... constant integer thingToLookFor = 5. ...
    (comp.lang.pl1)
  • Re: LOCALISATION
    ... is required after the loop is executed. ... constant integer thingToLookFor = 5. ... constant integer badIndex = -1. ... when an exception occurs in that loop, ...
    (comp.lang.pl1)
  • Re: LOCALISATION
    ... In case the loop is not executed at all. ... To make the value of the CV visible to the exception handler. ... Why not PL/I, I wonder. ... constant integer thingToLookFor = 5. ...
    (comp.lang.pl1)