Big Lesson on MQL5

 

I was converting my own indicator from MQL4 to MQL5 and while I'm pretty good at both standards, the result in MQL5 was wildly different. the culprit was some uninitialized local variables inside loops, that which worked well under MQL4 but crazy under MQL5.


// Something like this in MQL4 will always return X=0;

for (int i = 10; i > 0; i--) {

    int X;

    Print(X); // this would always print 0
   
    X = 999;
}


// On the other hand in MQL5 you would have

for (int i = 10; i > 0; i--) {

    int X;

    Print(X); // this prints 8 at the first loop and 999 for the rest of the loop
   
    X = 999;
}



Always explicitly initialize local variables or else MQL will surprise you again.

 
hematinik:

I was converting my own indicator from MQL4 to MQL5 and while I'm pretty good at both standards, the result in MQL5 was wildly different. the culprit was some uninitialized local variables inside loops, that which worked well under MQL4 but crazy under MQL5.




Always explicitly initialize local variables or else MQL will surprise you again.

if i am not mistaken, the ide does give you a warning of this when you compile it.

 
Big lession: Always assign the value to the variable before using it
 
Le Minh Duc #:
Big lession: Always assign the value to the variable before using it

dont worry; been there done that. But i learn it again and again and again... ... ...!!!!

 
Michael Charles Schefe #:

if i am not mistaken, the ide does give you a warning of this when you compile it.

It indeed does :) the "yeah you keep saying that like Im a fool" me never cared though