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
expression1, expression2, expression3) can be omitted.expression2 is omitted, it is considered perpetually true, creating an infinite loop.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
IsStopped() function within the loop body.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];