global variable inside a function?

 

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.

???

 
why not using a static variable?
 

what's that?

 

Look it up

 

"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?

 

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);
} 


Reason: