Syntax problem with Arrays

 

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};
 
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...
 
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;
}
 

Well you could use a switch instead.

 

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]);
     }
 
Keith Watford:

Not more elegant but more versatile.

Definitely more elegant. :)