Download MetaTrader 5

const variables

To add comments, please log in or register
Angus Hiseh
Angus Hiseh  


 I am a little bit confused with the use of const inside a function, as an example below. The document says the following "The const specifier declares a variable as a constant, and does not allow to change this variable during runtime. A single initialization of a variable is allowed when declaring it."

 My questions:

  1. Is the purpose of const to stop the variable from being modified?
  2. what is the significance of the ampersand, e.g. &time[] below? what is the difference between that and variables without ampersand, e.g. rates_total? 

int OnCalculate (const int rates_total,      // size of input time series
                 const int prev_calculated,  // bars handled in previous call
                 const datetime& time[],     // Time
                 const double& open[],       // Open
                 const double& high[],       // High
                 const double& low[],        // Low
                 const double& close[],      // Close
                 const long& tick_volume[],  // Tick Volume
                 const long& volume[],       // Real Volume
                 const int& spread[]         // Spread
Angus Hiseh
Angus Hiseh  

I found the answer....



Parameters of simple types are passed by value, i.e., modifications of the corresponding local variable of this type inside the called function will not be reflected in the calling function. Arrays of any type and data of the structure type are always passed by reference. If it is necessary to prohibit modifying the array or structure contents, the parameters of these types must be declared with the const keyword.

There is an opportunity to pass parameters of simple types by reference. In this case, modification of such parameters inside the calling function will affect the corresponding variables passed by reference. In order to indicate that a parameter is passed by reference, put the & modifier after the data type. 

To add comments, please log in or register