Array out of range

 

Hey guys,

I am new to this forum and I have a question about this code:

#property indicator_chart_window
#property indicator_buffers 3
#property indicator_color1 DeepSkyBlue
#property indicator_color2 DeepSkyBlue
#property indicator_color3 DeepSkyBlue

extern int BandsPeriod = 20;
extern int BandsShift = 0;
extern int BandsMethod = 1;
extern int BandsPrice = 0;
extern int Deviations = 1;



//---- buffers
double EMA[];
double UpperBand[];
double LowerBand[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int init()
  {
//---- indicators
   SetIndexStyle(0,DRAW_LINE);
   SetIndexBuffer(0,EMA);
        SetIndexLabel(0,"EMA");

   SetIndexStyle(1,DRAW_LINE);
   SetIndexBuffer(1,UpperBand);
   SetIndexLabel(1,"UpperBand");

   SetIndexStyle(2,DRAW_LINE);
   SetIndexBuffer(2,LowerBand);
   SetIndexLabel(2,"LowerBand");


//----
   return(0);
  }
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int start()
  {
   int counted_bars = IndicatorCounted();
   
   int CalculateBars = Bars - counted_bars;
   
   for (int Count = CalculateBars; Count>= 0;Count--)
          {
              EMA[Count] = iMA(NULL,0,BandsPeriod,BandsShift,BandsMethod,BandsPrice,Count);
              
              double StdDev = iStdDev(NULL,0,BandsPeriod,BandsShift,BandsMethod,BandsPrice,Count);
              
              UpperBand[Count] = EMA[Count] + (StdDev * Deviations);
              LowerBand[Count] = EMA[Count] - (StdDev * Deviations);
          }


//----
   
//----
   return(0);
  }
//+------------------------------------------------------------------+

I get an "Array out of range" error. This is not my code. I managed to get it working by editing the for loop to count upwards.

I am just curious why the author of this code decided to code the for loop in this way, and why is it now producing an array out of range error. Please advise.

 
Bars is the count of bars, the first bar's index is zero, that means the last bar's index is Bars-1 You start your loop from Bars, there is no bar with that index.
 
SDC:
Bars is the count of bars, the first bar's index is zero, that means the last bar's index is Bars-1 You start your loop from Bars, there is no bar with that index.
Thank you for your reply SDC.
Reason: