MQL4 Loop Operator do while

Overview

The do-while loop in MQL4 is a control flow statement that executes a block of code (the operator) at least once, and then repeatedly executes the block as long as a specified boolean expression evaluates to true. The condition is checked at the end of each iteration.

Syntax

do
   operator;
while(expression);

Behavior

1. **Execution**: The operator (loop body) is executed. 2. **Condition Check**: The expression is evaluated. 3. **Repetition**: If the expression is true, the loop returns to step 1. 4. **Termination**: If the expression is false, the loop terminates.

This guarantees that the loop body is executed at least one time, unlike for and while loops which check the condition before the first iteration.

Constraints and Considerations

  • **Infinite Loops**: Ensure the expression eventually becomes false. An infinite loop can occur if the condition never evaluates to false. The example demonstrates incrementing a counter (i++) to prevent this.
  • **Program Termination**: For loops that might run for a large number of iterations, it is advisable to check for forced program termination using the IsStopped() function within the loop condition to prevent unexpected behavior or resource issues.
  • Example

    // Calculate the Fibonacci series
    int counterFibonacci = 15;
    int i = 0, first = 0, second = 1;
    int currentFibonacciNumber;

    do   {     currentFibonacciNumber = first + second;     Print("i = ", i, " currentFibonacciNumber = ", currentFibonacciNumber);     first = second;     second = currentFibonacciNumber;     i++; // without this operator an infinite loop will appear!   } while(i < counterFibonacci && !IsStopped());

    Related Operators

  • [Loop Operator for](/basis/operators/for)
  • [Loop Operator while](/basis/operators/while)
  • [Break Operator](/basis/operators/break)
  • [Continue Operator](/basis/operators/continue)
  • 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)