Whiler
Whiler

Reputation: 8086

E1012 Constant expression violates subrange bounds ; why does it work with variable?

program Project1;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils;

var
  ints: array[1..2] of Integer = (0,0);
  i   : Integer;

begin
  ints[5] := 10;    // doesn't compile
  i := 5;
  ints[i] := 10;    // Seems to works
  Writeln(ints[i]); // and even display the value
  Readln;
end.

I have set a bound to the array ints.

Usually, I check the Low(ints) and High(ints) before trying to set a value to a bounded array... But as I was looking to another piece of code, I notice that I can use index outside from the boundary and that it doesn't raise any exception...

I'd like to know why it works and what are the consequence? (for example, if this part of memory is not reserved and I can corrupt it, ...)

I have searched for others questions but haven't found the good one... if it's exist, do not hesitate to put the link and close this one, thanks.

Upvotes: 4

Views: 2787

Answers (1)

David Heffernan
David Heffernan

Reputation: 612993

Because the compiler does not perform data flow analysis. In order for the compiler to reject this code it would need to analysis your code and be sure that i was out of bounds and the compiler simply does not do so. To do so for even moderately more complex examples would require a very significant effort from the compiler developers.

Since this code will fail with a runtime error if you switch range checking on, I personally feel that there is little to be gained by adding such data flow analysis to the compiler. If you are not running with range checking enabled, then you really should be.

One of the numerous benefits about getting the compiler to perform range checking is that in many cases you can expunge your range checking code. This will make your code much clearer. However, you can only do this when you are in full control of the index and can analyse the code statically. If the index comes from user input, then clearly you need to provide protection against abuse.

You ask what are the consequences of running this code without range checking. Well, the behaviour is not defined and really anything could happen. Worst case scenario is that the program always works for you but fails in a critical way for your most important clients.

Upvotes: 6

Related Questions