MetaQuotesLanguage and references

It would often be very useful (mainly for optimization) if a MQL function could return several values at once.

Unfortunately, MQL doesn’t support object oriented programming, it has no structures, neither. However, the situation is not so dramatic, because we can use passing by reference to achieve similiar results. But firstly, I will explain passing by value. I assume that we have two variables and a sample function:

int x=1;
int y=2;

void f(int a, int b) {
 a+=5;
 b-=5;
}

void start() {
 f(x,y);
 Print(x+" "+);
}

If we call f(x,y) from the start() function, then nothing will happen to x and y – i.e. there will be 1 and 2 printed in the log, which are the initial values of x and y.

The numbers won’t change, because by default the values of x and y will be copied, which looks as the platform had assigned a=x and b=y before it called the function. And because a and b have local scope limited to function body, any changes made to them are seen only inside this function.

In case of a reference it looks like this:

int x=1;
int y=2;

void g(int& a, int& b) {
 a+=5;
 b-=5;
}

void start() {
 g(x,y);
 Print(x+" "+y);
}

Here, the key is “&” operator, which means that the parameter is passed by reference. It means that when calling g(x,y), “assignments” a=x and b=y are made, then the function is executed and after that reverse “assignments” x=a and y=b are made. The end result is that numbers 6 and -3 are printed in the log.

Of course, references do not affect the values returned directly (by return statement) so we can use both ways at the same time.

I hope I managed to explain clearly the way references work, however, I advise you to play with them for a while to learn how it all works and how to use it.

In the coming days, I will present a function, which will show, how references work in real life and how to make your code more efficient by using them.

Share with your friends:

Send us your comments

Name (required)

Email (required)

Message

  • Facebook