Error 10. Subscript out of range. You must not access array elements outside 0..(BarCount-1) range

Occurs when you attempt to access array elements with subscripts below 0 (zero) or above BarCount-1.

// incorrect
for( bar = 0; bar < BarCount; bar++ )
{
   a[ bar ] =
C[ bar - 1]; // when i == 0 we are accessing C[-1] which is wrong
}


// correct
for( bar = 0; bar < BarCount; bar++ )
{
   
if( bar > 0 )
       a[ bar ] =
C[ bar - 1 ];   // only access C[ i - 1 ] when i is greater than zero
   
else
       a[ bar ] =
C[ 0 ];
}

One of most common mistakes is using hard coded upper limit of for loop and assuming that all symbols have enough quotes.

For example:

MyPeriod = 10;

for( i = 0; i < MyPeriod; i++ ) // WRONG ! this assumes that you always have at least 10 quotes !
{
  
// ... do something
}

This will always fail on symbols that have less quotes than 10 and it may also fail if you zoom your chart in so less than 10 quotes are actually displayed on the chart.

To ensure error-free operation you must always check for upper index being LESS than BarCount, like shown in the code below:

MyPeriod = 10;

for( i = 0; i < MyPeriod AND i < BarCount; i++ ) // CORRECT - added check for upper bound
{
  
// ... do something
}

Alternativelly you can enter the loop only when there are enough bars, like shown in this code:

MyPeriod = 10;

if( MyPeriod <= BarCount ) // CORRECT - check if there are enough bars to run the loop
{
 for( i = 0; i < MyPeriod; i++ )
 {
  
// ... do something
 }
}