Static Variables

Declaration

  • Declared using the static keyword before the data type.
  • Example: static int flag = 10;
  • Initialization

  • Can be initialized by a constant or constant expression corresponding to its type.
  • If initial values are not specified, they take zero initial values.
  • Initialized only once after the program is loaded.
  • Lifetime and Scope

  • **Local Static Variables:** Retain their values throughout the function lifetime. Contain values from the previous call on subsequent calls.
  • **Scope:** Local to the block in which the variable is defined.
  • **Lifetime:** The lifetime of the MQL4 program (same as global variables).
  • Usage

  • Any variables in a block, except formal parameters, can be defined as static.
  • Unlike non-static local variables, which are allocated on the program stack, static variables have a program-wide lifetime.
  • 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); }

    Related Concepts

  • Data Types
  • Initialization of Variables
  • Visibility Scope and Lifetime of Variables
  • Static Class Members