Search code examples
pass-by-referencemql4

How to assign method output to variable by reference MQL4


I'm guessing this question is going to apply to many similar languages other than MQL4 such as c++ (which I also forget how to use) which require you manually specify when you are passing by reference.

Method reference:

int[] previous = GetPrevious(i, ZigZagBuffer);

Method definition:

int GetPrevious[](int current, const double& buffer[])
{
   int count = 0;
   int result[];
   // calculate count
   ArrayResize(result,count);
   // fill array
   return result;
}

The resulting compile error is:

"Invalid Array Access"

From what I understand, this is because array's can only be passed by reference, but you have to explicitly state that you are passing it by reference. But the more I look up the syntax for passing by reference, the more I find articles about passing parameter by reference. (which I already know how to do as you can see in the code example.)

What is the syntax to assign the output of a method to a variable?

In case it matters, I only need to read the array multiple times; I'm not needing to alter or re-assign it after it is declared.


Solution

  • You cannot return array. You have to create it and pass into the function, fill inside the function and that's it.

    OnTick(){
       double array[];                 //declaration of the array
       fillArray(array,10);            //passing array by ref, updating it there
       Print(array[0]=0 && array[9]=9);//returns true
    }
    
    void fillArray(double &array[],int size){
       ArrayResize(array,size);
       for(int i=0;i<size;i++){array[i]=i;}
    }