Out-of-Bounds Array Indices

QUESTION: OK, here is a weird thing I don't understand. Consider the following array.

   IDL> array = Indgen(10)

If I want to print certain of the array elements, I can specify the indices as a vector, like this.

   IDL> indices = [2, 5, 9]
   IDL> Print, array[indices]
       2       5       9

All as expected. But, if I make a typing mistake and do this, why is there no error?

   IDL> indices = [2, 5, 99]
   IDL> Print, array[indices]
       2       5       9

In fact, any out-of-bounds index is truncated to the nearest valid index.

   IDL> indices = [-20, 15, 168]
   IDL> Print, array[indices]
       0       9       9

Can this be right!?

ANSWER: Well, it is hard to say if it is “right” or not. It is a long-time feature of IDL, although not well-known by even the most experienced IDL users. Note that this kind of out-of-bounds subscript truncating only occurs if the subscript indices are in an vector. In other words, the following code does generate an error.

   IDL> Print, array[99]
   % Attempt to subscript ARRAY with <LONG(99)> is out of range.

If you wish to always generate errors when out-of-bound subscripts are used, you can set the strictarrsubs compiler option, like this. Of course, you will have to set the compiler option in each of the IDL program modules where you wish to have this functionality.

   IDL> Compile_Opt strictarrsubs
   IDL> indices = [2, 5, 99]
   IDL> Print, array[indices]
   % Array used to subscript array contains out of range subscript: ARRAY.

Version of IDL used to prepare this article: IDL 7.1.

Google
 
Web Coyote's Guide to IDL Programming