Switch Operator


for example, forex

Rather often it is required to have more than two scenarios in an Expert Advisor. For example the variable i may take on integer values from 1 to 5 and depending on the value this variable takes on 5 different sequences of operators are possible. Such a task is easy to resolve by using nested conditional operators if-else.

   if (i == 1)
       operator 1;
   else
       if (i == 2)
          operator 2;
       else
          if (i == 3)
             operator 3;
          else
             if (i == 4)
                 operator 4;
             else
                if (i == 5)
                   operator 5;

Such a code will work, but it is very difficult to read and perceive. For illustration purposes in such cases it is better to use the operator of switching switch.

The format of the switch operator:

   switch(expression)
     {
       case constant1: operators1
       case constant 2: operators 2
         ...
       default: operators_default
     }

The principle of the work of this operator: at first the value of «expression» is calculated, then the constant that is equal to the result of the «expression» is sought among constants «constant1», «constant2» etc. If such a constant is found the control is transferred to the corresponding group of operators. After that all the operators of this group and of all the next groups are executed one by one, until the last operator in the switсh operator is executed or the switch operator is terminated with the help of the break operator. If such a isn’t found the control is transferred to the group of operators «operators_default».

The default mark and the group of operators «operators_default» may be lacking. In such a case no actions will be executed, if none of the constants equals to the result of the «expression». Default not necessarily must be the last one.

Each variant case may be marked by an integral constant, character constant or constant expression.

Now we will rewrite our example with the variable i and 5 variants of actions with the help of the switch operator:

   switch (i)
     {
       case 1:  operator1; break;
       case 2:  operator2; break;
       case 3:  operator3; break;
       case 4:  operator4; break;
       case 5:  operator5; break;
     }


Next article: "How to teach the Expert Advisor to trade"

+7 (495) 710-76-76
© 1998—2008 «Alpari»

close

Your Personal Area

For alpari.classic enter your account number (a letter and 4 figures) and the code word for the Personal Area.

For alpari.micro account: enter your login (6 figures) and the password for MT.

Open an account!Forgotten your password?