MQL4 Reference Language Basics Variables Static Variables

Static Variables

The storage class of static defines a static variable. The static modifier is indicated before the data type.

Example:

int somefunc()
  {
   static int flag=10;
   ...
   return(flag);
  }

A static variable can be initialized by a constant or constant expression corresponding to its type, unlike a simple local variable, which can be initialized by any expression.

Static variables exist from the moment of program execution and are initialized only once after the program is loaded. If the initial values are not specified, variables of the static storage class are taking zero initial values. The scope of the static variables is the same as the scope of the global variables: the lifetime of the mql4-program. The scope of a static variable is local to the block in which the variable is defined.

Local variables declared with the static keyword retain their values throughout the function lifetime. With each next function call, such local variables contain the values that they had during the previous call.

Any variables in a block, except formal parameters of a function, can be defined as static. If a variable declared on a local level is not a static one, memory for such a variable is allocated automatically at a program stack.

Example:

int Counter()
  {
   static int count;
   count++;
   if(count%100==0) Print("Function Counter has been called ",count," times");
   return count;
  }
void OnStart()
  {
//---
   int c=345;
   for(int i=0;i<1000;i++)
     {
      int c=Counter();
     }
   Print("c =",c);
  }

See also

Data Types, Encapsulation and Extensibility of Types, Initialization of Variables, Visibility Scope and Lifetime of Variables, Creating and Deleting Objects, Static Class Members