- Questions on OOP in MQL5
- Variable Initialization
- Question About Global(scope) Variables of indicators
I know this has been asked alot of times, i've also watched several videos and have read informations about static variable but i still can't seem to comprehend it. This is my knowledge so far about it, it is initialized only once just like the global variable, but it is limited to the scope of the function you have placed it.
when you call a function any variables declared inside the function will be deleted and their memory freed when the function closes. They will be recreated and declared anew if the function is called again.
So if there are some variables you wish to retain the value of for next time the function is called, then you need to declare them static to ensure their value is maintained.
Example a simple counter in the function to state how many times the function has been called.
Try running the script below with and without "static" and you will see.
A variable declared at the global level is available throughout a program and will retain it value. So use global if the variable needs to retain it's value between functions and is used in multiple functions, use static if it is only used in the one function and needs to retain it's value between calls.
regards
void OnStart() { for(int iC=1; iC < 20; iC++) { DoFunction(); } } void DoFunction() { static int Called = 0; Called += 1; Print("Function called: " + Called + " times"); }
- Free trading apps
- Over 8,000 signals for copying
- Economic news for exploring financial markets
You agree to website policy and terms of use