Download MetaTrader 5
To add comments, please log in or register
Join MQL5 Cloud Network. Millions of traders are waiting for this!
SteelAce
173
SteelAce 2014.10.07 05:58 

Sorry being so fool, but I cannot find switch command syntax in https://www.mql5.com/en/docs. When I write code


 ENUM_TIMEFRAMES SetPeriodName (string period){
  switch(period)
     {
      case "M1"     : return(PERIOD_M1);
      case "M2"     : return(PERIOD_M2);

      ...

      case "Daily"  : return(PERIOD_D1);
      case "Weekly" : return(PERIOD_W1);
      case "Monthly": return(PERIOD_MN1);
      default  : Print("  cannot set period")
      }

   }

compiler shows error 'period' illegal switch expression type

I don't belive my eyes. Is it indeed restricted using string variables in switch cases or is it something else? I want to convert string values to corresponding timeframe values.

MQL5 Reference - How to use algorithmic/automated trading language for MetaTrader 5
MQL5 Reference - How to use algorithmic/automated trading language for MetaTrader 5
  • www.mql5.com
MetaQuotes Language 5 (MQL5) Reference - Documentation on MQL5.com
SteelAce
173
SteelAce 2014.10.07 09:37  
Really I have found way to go around that problem but it is still interesting why switch don't eat string variables.
Biantoro Kunarto
14591
Biantoro Kunarto 2014.10.07 09:52  

This link will show you the switch syntax : https://www.mql5.com/en/docs/basis/operators/switch, I think your problem is :

Switch Operator

Compares the expression value with constants in all the case variants and passes control to the operator that corresponds to the expression value. Each variant of case can be marked with an integer constant, a literal constant or a constant expression. The constant expression can't contain variables or function calls. Expression of the switch operator must be of integer type. 

You can't use string type for switch operator.

Documentation on MQL5: Language Basics / Operators / Switch Operator
Documentation on MQL5: Language Basics / Operators / Switch Operator
  • www.mql5.com
Language Basics / Operators / Switch Operator - Reference on algorithmic/automated trading language for MetaTrader 5
Biantoro Kunarto
14591
Biantoro Kunarto 2014.10.07 09:53  
You can use "if" instead of "switch"
Stuart Browne
5704
Stuart Browne 2014.10.07 11:00  
As said above, switch expression must be integer. (kind of strange that the example uses string). Just use ifs
Alain Verleyen
Moderator
30183
Alain Verleyen 2014.10.07 11:43  
Filter:
As said above, switch expression must be integer. (kind of strange that the example uses string). Just use ifs
The example use character constants not string.
Stuart Browne
5704
Stuart Browne 2014.10.07 11:47  
angevoyageur:
The example use character constants not string.
Good point!
/
To add comments, please log in or register