Switch Operator

Overview

The switch operator in MQL4 provides multi-way branching. It evaluates an expression and compares its value against a series of constant case labels. Control is transferred to the code block associated with the first matching case.

Syntax

switch(expression)
{
  case constant:
    operators
  case constant:
    operators
    ...
  default:
    operators
}

Expression Requirements

  • The expression within the switch() must be of an integer type.
  • Case Labels

  • Each case label must be followed by a constant value.
  • Constants can be integer constants, literal constants, or constant expressions.
  • Constant expressions cannot contain variables or function calls.
  • Constant expressions are evaluated during compilation.
  • No two constants within a single switch operator can have the same value.
  • Default Case

  • The default label is optional.
  • If no case constant matches the expression value and a default label exists, control transfers to the default block.
  • If no match is found and default is absent, no actions are executed.
  • Execution Flow

  • When a case label matches the expression, the associated operators are executed.
  • Execution continues sequentially into subsequent case blocks (fall-through) unless a break operator is encountered.
  • The break operator terminates the switch statement execution.
  • This fall-through behavior allows binding a sequence of operators to multiple case variants.
  • Constraints

  • Duplicate constants within a single switch statement are not allowed.
  • Constant expressions are evaluated at compile time.
  • Related Concepts

  • [Break Operator](/basis/operators/break)
  • [Integer Types](/basis/types/integer/integertypes)
  • Examples

    // Example 1: Basic switch with break
    int x = 'A';
    switch(x)
      {
       case 'A':
         Print("CASE A");
         break;
       case 'B':
       case 'C':
         Print("CASE B or C");
         break;
       default:
         Print("NOT A, B or C");
         break;
      }

    // Example 2: Fall-through and default behavior string res = ""; int i = 0; switch(i) { case 1: res = i; break; default: res = "default"; break; case 2: res = i; break; case 3: res = i; break; } Print(res); // Output: default

    Platform Support

  • MQL4 Language
  • See Also

  • [Initialization of Variables](/basis/variables/initialization)
  • [Visibility Scope and Lifetime of Variables](/basis/variables/variable_scope)
  • [Creating and Deleting Objects](/basis/variables/object_live)
  • [Ternary Operator ?:](/basis/operators/ternary)
  • [Loop Operator while](/basis/operators/while)