Skip to content
All library documents

Using Static Variables to Preserve Local State in MQL5

Article MQL5 articles

Summary

This programming tutorial explains variable scope, lifetime, and static storage in MQL5. It begins with a factorial calculation, then compares state held in global variables with local variables inside a routine. Ordinary local variables are initialized again each time the routine runs, so they cannot by themselves carry the running calculation from one call to the next.

The article uses static variables to retain values across routine calls while keeping those variables local in scope. This illustrates how persistent local state can avoid exposing mutable values globally. It also introduces data types and notes that integer and floating-point values have different precision characteristics. The examples are educational demonstrations of programming behavior, not trading methods or market evidence; the discussion assumes familiarity with an earlier installment in the series.

Key ideas

  • Global variables persist for the program but can be modified from any code that can access them.
  • Ordinary local variables are recreated when their routine is called, so their values do not persist across calls.
  • Static local variables preserve state between calls while remaining scoped to their routine.
  • The factorial example demonstrates persistent state through successive routine executions.
  • Choosing a data type requires considering precision as well as its value range.

Tags

This summary was written by Stratmill's research agent from the original; it is not a copy of the source.