Syntax problem with Arrays

To add comments, please log in or register
Marbo
503
Marbo  

Hi guys,

can anyone tell me how the correct syntax looks like?

int timeframes[3];
if (_Period==PERIOD_W1) timeframes[3]={PERIOD_D1, PERIOD_H4, PERIOD_H1};
else if (_Period==PERIOD_D1) timeframes[3]={PERIOD_H4, PERIOD_H1, PERIOD_M30};
else if (_Period==PERIOD_H4) timeframes[3]={PERIOD_H1, PERIOD_M30, PERIOD_M15};
Marco vd Heijden
Moderator
12737
Marco vd Heijden  
MQL5 Programming Basics: Arrays
MQL5 Programming Basics: Arrays
  • www.mql5.com
Arrays are an integral part of almost any programming language along with variables and functions. Many novice programmers are often afraid of arrays. It sounds strange but it is true! I can assure you that they are not scary at all. In fact, arrays are similar to regular variables. Without going into detail about the notation peculiarities...
Marbo
503
Marbo  
Marco vd Heijden:

Please read here https://www.mql5.com/en/articles/567

Ok, I see. The array can only be initialized once generally and then I have to fill it according to my conditions?

Is this the only way? Doesn't look very elegant... :D

if (_Period==PERIOD_W1) {
   timeframes[0]=PERIOD_D1;
   timeframes[1]=PERIOD_H4;
   timeframes[2]=PERIOD_H1;
}
else if (_Period==PERIOD_D1) {
   timeframes[0]=PERIOD_H4;
   timeframes[1]=PERIOD_H1;
   timeframes[2]=PERIOD_M30;
}
else if (_Period==PERIOD_H4) {
   timeframes[0]=PERIOD_H1;
   timeframes[1]=PERIOD_M30;
   timeframes[2]=PERIOD_M15;
}
Marco vd Heijden
Moderator
12737
Marco vd Heijden  

Well you could use a switch instead.

Keith Watford
Moderator
20586
Keith Watford  

Not more elegant but more versatile.

   int timeframes[];
   int TF_Array[]= {PERIOD_MN1,PERIOD_W1,PERIOD_D1, PERIOD_H4, PERIOD_H1,PERIOD_M30,PERIOD_M15,PERIOD_M5,PERIOD_M1};
   int x=0;
   for(; x<9; x++)
      if(TF_Array[x]==_Period)
         break;
   if(x>5)
      Print("Error - Current TF is too low");
   else
     {
      int count=ArrayCopy(timeframes,TF_Array,0,x+1,3);
      Print("Copied = ",count);
      for(x=0; x<count; x++)
         Print("TF ",x+1," is ",timeframes[x]);
     }
Marbo
503
Marbo  
Keith Watford:

Not more elegant but more versatile.

Definitely more elegant. :)

To add comments, please log in or register