I’m reading some Pascal code and everything is pretty straightforward except subranges. In the program I’m reading there’s a variable d
with the following type declaration:array[0..22] of 0..15
; there’s then the following procedure:
var a:integer;
begin
a:=0;
while k>0 do
begin
k:=k-1;
a:=(a+dig[k]*two) div 10;
end;
round_decimals:=(a+1) div 2;
end;
Where k
is a variable of type 0..63
. So since k
can be above the range of the index of dig
how does this code work? — It’s a routine for doing fixed point arithmetic and so I would assume the array indicie overflows in some controlled manner, but if anybody could explain the exact behavior I’d be really happy. Also, do Pascal arrays assign in some known manner? There were a lot of versions of Pascal and I think this program is written in a pretty “Pascal-version agnostic” manner, but I can’t find much explanation on the subtle semantics of subrange expressions.
5
It depends on the Pascal variant. In managed versions, like Oxygene or the DWS scripting language, assigning out of bounds of an array will always raise an exception at runtime. In Delphi and FPC, assigning out of bounds of an array should raise an exception at runtime, and does by default, but there’s an option to turn bounds checking off via a compiler directive. The behavior of other Pascal compilers will vary, based on whether or not they generate bounds checking code.
5
Figured it out; the ranges were chosen for alignment/offsets. Since Pascal (at least the old version of Pascal I’m reading) doesn’t have short ints, etc. this was the alternative. Glad I don’t write Pascal code. Anyway, it really had nothing to do with bounds checking and d[…] was pre-loaded in case anybody is wondering (I doubt it). Case closed.