# Subranges in Pascal

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.

• `decr(k)`? What flavor of Pascal is this? I'm familiar with `dec()`, but not `decr()`... Commented May 21, 2013 at 17:35
• It's written in an intentionally-generic flavor of Pascal. `decr(k)` is just an alias for `k := k - 1`. I've modified the original, as you correctly point out that is obscure usage. Sorry about that. Commented May 21, 2013 at 17:37
• Since k is only decremented towards zero, it doesn't matter what its range is, so long as it starts below the top bound of the array being indexed. Commented May 21, 2013 at 20:25
• The versions of Pascal I've worked with (don't ask me how long ago!!) did not strongly check the declared ranges of variables on assignment or use as an array index -- there might be a compiler warning but that was it. Rather, runtime checks were performed on the array index (unless disabled). Commented May 21, 2013 at 20:28
• (Subranges were mostly useful as the basis of sets. Pascal had one of the best set implementations I've ever seen.) Commented May 21, 2013 at 20:29

• I find this unfathomable because I just wrote a quick loop: `begin for i:=0 to 63 do writeln(d[i]) end.` and got no such runtime exceptions. Commented May 21, 2013 at 17:45
• I tried it in Free Pascal without any modifications... it gave me a bounds warning (not error[!]) when I tried to assign `i > 63`, but not when I looped `i` out of the `0..22` index range. Commented May 21, 2013 at 18:38