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
expression within the switch() must be of an integer type.Case Labels
case label must be followed by a constant value.switch operator can have the same value.Default Case
default label is optional.case constant matches the expression value and a default label exists, control transfers to the default block.default is absent, no actions are executed.Execution Flow
case label matches the expression, the associated operators are executed.case blocks (fall-through) unless a break operator is encountered.break operator terminates the switch statement execution.case variants.Constraints
switch statement are not allowed.Related Concepts
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
See Also
Previous
arrow_back
Ternary operator