Search code examples
mql4

why need to use array function in mql4


I really not satisfied with mql4 array function.In mql4 reference they cannot explain why need to use this function. example why I need to use arrayinitialize function


Solution

  • When you declare some array, it may contain some garbage there. Most likely you will have default values, like 0 or NULL but garbage may stay there as well. By use of 'ArrayInitialize()` function you can be sure that all the values in your array are the values you've put there.

    string arr2str(const int &array[])//fn to print array, ugly, ends with ,|
      {
       string result="|";
       for(int i=0;i<ArraySize(array);i++)
         {
          result+=(string)i+"="+(string)array[i]+", ";
         }
       return result+"|";
      }
    void OnTick()
      {
    
       int array[8];
       printf("1: %d. %s",ArraySize(array),arr2str(array));
       //receive: 1: 8. |0=0, 1=0, 2=0, 3=0, 4=1995110657, 5=146315416, 6=1, 7=85975080, |
       int result=ArrayInitialize(array,7);
       printf("2: %d %d. %s",result,ArraySize(array),arr2str(array));
       //receive: 2: 8 8. |0=7, 1=7, 2=7, 3=7, 4=7, 5=7, 6=7, 7=7, |
    
       ExpertRemove();//to stop the test
      }
    

    As you can see, first array output (1:) has some strange data. After initialization, no problem with it (2:) - all are sevens since I put 7 as second param in the function, it could be and most likely 0 instead of 7 in your codes.