MQL4 - automated forex trading   /  

Forum

global variable inside a function?

Back to topics list To post a new topic, please log in or register

avatar
124
inkexit 2010.09.04 23:25 

can you declare a global variable inside a function?

I have functions that do a lot of processing, and then compare that with the results they got last time. To compare results, I must store some of the data as variables that wil remain constant when ever the finction is called. Therefore I must declare these global variables outside of the function. But that makes for sloppy looking code, imo, and if i want to use the function in the future in other programs, i might forget to declare the global variable that makes it work.

???

Using Neural Networks In MetaTrader

Using Neural Networks In MetaTrader

This article shows you how to easily use Neural Networks in your MQL4 code taking advantage of best freely available artificial neural network library (FANN) employing multiple neural networks in your code.


avatar
1975
zzuegg 2010.09.05 00:02 
why not using a static variable?

avatar
124
inkexit 2010.09.05 00:31 

what's that?


avatar
2646
phy 2010.09.05 00:36 

Look it up


avatar
124
inkexit 2010.09.05 02:27 

"Static variables are stored in the permanent memory, their values do not get lost when the function is exited. Any variables in a block, except for formal parameters of the function, can be defined as static. The static variable can be initialized by a constant of the corresponded type, unlike a simple local variable which can be initialized by any expression. If there is no explicit initialization, the static variable is initialized with zero. Static variables are initialized only once before calling of the "init()" function, that is at exit from the function inside which the static variable is declared, the value of this variable not getting lost."

Looks like what I need. Though the english is a bit confusing. What does it mean that it initializes only once before the init() but AFTER the exit of the function? Isnt the init() always run first?


avatar
2646
phy 2010.09.05 07:28 

Sounds like:

MT4 Core calls an internal function to cause your code to run...

Your Static Variables are initialized.

Your init() is called.

tick arrives.

Your start() is called. count = 1

tick arrives.

Your start() is called. count = 2

tick arrives.

Your start() is called. count = 3

-----------------------

start(){  

   int count;
   count = myFunction();
   Comment("Count = ", count);

   return(0);
}
 



int myFunction(){
   static int runCount = 0;
   runcount++;
   return(runCount);
} 


Back to topics list  

To add comments, please log in or register