MQL4 For Loop Operator

Overview

The for loop operator in MQL4 facilitates iterative execution of a block of code.

Syntax

for(expression1; expression2; expression3)
  operator;

  • expression1: Initializes the loop (e.g., variable declaration/assignment).
  • expression2: Condition checked before each iteration. If true, the loop body executes; if false, the loop terminates.
  • expression3: Executed after each iteration (e.g., increment/decrement).
  • operator: The code block or single statement to be executed.
  • Equivalence to While Loop

    The for loop is semantically equivalent to the following while loop structure:

    expression1;
    while(expression2)
      {
        operator;
        expression3;
      }
    

    Expression Omission

  • Any of the three expressions (expression1, expression2, expression3) can be omitted.
  • Semicolons separating the expressions must always be present.
  • If expression2 is omitted, it is considered perpetually true, creating an infinite loop.
  • The for(;;) construct is an infinite loop, equivalent to while(1).
  • Comma Operator

  • expression1 or expression3 can comprise multiple expressions combined using the comma operator (,).
  • Handling Long Iterations

  • For loops expected to run many times, it is recommended to check for program termination using the IsStopped() function within the loop body.
  • If IsStopped() returns true, break can be used to exit the loop.
  • Examples

    1. **Standard Iteration:**

        for(x=1; x<=7000; x++)
          {
            if(IsStopped()) break;
            Print(MathPower(x,2));
          }
        

    2. **Infinite Loop with Termination Condition:**

        for(; !IsStopped(); )
          {
            Print(MathPower(x,2));
            x++;
            if(x > 10) break;
          }
        

    3. **Multiple Expressions with Comma Operator:**

        for(i=0, j=n-1; i < n && !IsStopped(); i++, j--)
          a[i] = a[j];
        

    Related Concepts

  • [Initialization of Variables](/basis/variables/initialization)
  • [Visibility Scope and Lifetime of Variables](/basis/variables/variable_scope)
  • [Creating and Deleting Objects](/basis/variables/object_live)
  • [Loop Operator while](/basis/operators/while)
  • [Loop Operator do while](/basis/operators/dowhile)
  • [Break Operator](/basis/operators/break)
  • [Continue Operator](/basis/operators/continue)