MQL4 If-Else Conditional Operator

Overview

The if-else operator is used for conditional execution of code blocks.

Syntax

if (expression)
    operator1
else
    operator2;

Behavior

  • If expression evaluates to true, operator1 is executed, and control proceeds to the statement following operator2.
  • If expression evaluates to false, operator2 is executed.
  • Optional Else Clause

    The else part can be omitted. When else is omitted in nested if statements, an else clause is associated with the nearest preceding if statement within the same block that does not have its own else clause.

    Examples

    **Example 1: Default else association**

    // else refers to the second if
    if(x > 1)
        if(y == 2) z = 5;
    else z = 6;
    

    **Example 2: Grouping with braces**

    // else refers to the first if
    if(x > 1)
        {
        if(y == 2) z = 5;
        }
    else z = 6;
    

    **Example 3: Nested if-else if**

    if(x == 'a')
        {
        y = 1;
        }
    else if(x == 'b')
        {
        y = 2;
        z = 3;
        }
    else if(x == 'c')
        {
        y = 4;
        }
    else
        Print("ERROR");
    

    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)
  • [Compound Operator](/basis/operators/compound)
  • [Expression Operator](/basis/operators/expression)
  • [Return Operator](/basis/operators/return)
  • [Ternary Operator ?:](/basis/operators/ternary)
  • [Switch Operator](/basis/operators/switch)
  • [Loop Operator while](/basis/operators/while)
  • [Loop Operator for](/basis/operators/for)
  • [Loop Operator do while](/basis/operators/dowhile)
  • [Break Operator](/basis/operators/break)
  • [Continue Operator](/basis/operators/continue)
  • [Object Create Operator new](/basis/operators/newoperator)
  • [Object Delete Operator delete](/basis/operators/deleteoperator)