Self-learning the MQL5 language from scratch - page 43

 
Реter Konow:
You've certainly made a big step forward in the main subject - you've mastered and begun to use functions, and congratulations to you, of course!)

At this rate, you'll soon be trailing...

I'm consolidating the material I've learned so far, as well as I've started studying for and while loops. Trailing, though in distant future, but it's an obligatory part of my self-study plan.

Regards, Vladimir.

 
MrBrooklin:

...

By and large, the script is written correctly. It does not take into account the null value of Period_learning, but otherwise it is good.

We need to add arguments and calculations to functions in order to "saturate" their work, because now they substitute one variable for another or just return a value without doing anything with it. As an example of using functions, this option is fine, but in reality the script should have a solvable task, which is not present in this example.

Therefore, I suggest either extending this script and making it more complex, or inventing and writing a new script that is more meaningful, full of calculations in functions and with a small if-else condition tree.

Think about what kind of problem it could solve.



 
Реter Konow:
By and large, the script is written correctly. It doesn't take into account the null value of Period_learning, but otherwise it's good.

We need to add arguments and calculations to the functions to make them "meaningful", because now they substitute one variable for another or just return a value without doing anything with it. As an example of using functions, this option is fine, but in reality the script should have a solvable task, which is not present in this example.

Therefore, I suggest either extending and complicating this script or coming up with and writing a new one that is more meaningful, full of calculations in functions and with a small if-else condition tree.

Think about what kind of problem it could solve.

Ok, Peter, I'll think how to complicate the script and apply if-else condition statement inside the function.

Regards, Vladimir.

 

Good day and good mood everyone!

I continue studying the MQL5 programming language. Taking into account the tips from Peter Konov, I am pasting the finalized code of the script that is a continuation of one of the tasks from the participants of this thread. The script has been tested in all modes. No problems detected. To begin with I applied the minimum number of input parameters. The script code is written in English, the comments to the code are in Russian, to ease the learning process. As I promised earlier, I tried to describe the script in a manner comprehensible to a pupil of the 1-st form of programming school.

Best regards, Vladimir.

//+------------------------------------------------------------------+
//|                                                Learning_MQL5.mq5 |
//|                        Copyright 2020, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright   "Copyright 2020, MetaQuotes Software Corp."
#property link        "https://www.mql5.com"
#property description "Скрипт подводит итог обучения языку программирования MQL5. В зависимости от"
#property description "входных параметров печатает во вкладке \"Эксперт\" торгового терминала два"
#property description "сообщения на русском языке: \"Я выучу язык MQL5!\" или \"Я не выучу язык MQL5!\""
#property description "Код скрипта написан на основе примера, приведенного Valeriy Yastremskiy на сайте"
#property description "MQL5, в теме \"Самообучение языку MQL5 с полного нуля\"."
#property description "======================================================"
#property description "Ссылка на пример https://www.mql5.com/ru/forum/352460/page30#comment_18646826"
//---
#property version     "1.00"              //версия скрипта 1.00
//---
#property script_show_inputs              //выводить окно со свойствами перед запуском скрипта 
//--- Зададим входные параметры скрипта:
input ushort Period_learning=500;         //Полный период обучения (в днях)
input ushort Days_passed=10;              //Сколько дней прошло с начала обучения (в днях)
input bool   Patience=true;               //Терпение (true - достаточно; false - не достаточно)
//--- Зададим глобальные переменные:
//переменная enough_time (достаточно времени), где bool - логическое значение: истина (true) или ложь (false)
bool enough_time;
//переменная enough_patience (достаточно терпения), где bool - логическое значение: истина (true) или ложь (false)
bool enough_patience;
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart() //старт работы скрипта
  {
   /* Зададим условие для работы скрипта. Если:
      1. значение функции "имею время" будет равно значению истина (true)
      2. и значение функции "имею терпение" будет равно значению истина (true)
   */
   if(have_time()==true && have_patience()==true)
     {
      Print("Я выучу язык MQL5!");    //выводим сообщение "Я выучу язык MQL5!"
     }
   else //в противном случае
     {
      Print("Я не выучу язык MQL5!"); //выводим сообщение "Я не выучу язык MQL5!"
     }
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//--- Функция "имею_время"
bool have_time()                 //создаём функцию "имею_время" и присвоим тип данных bool
  {
   /* Если:
      1. значение входного параметра Period_learning больше нуля
      2. и значение входного параметра Days_passed больше или равно значения входного параметра Period_learning
   */
   if(Period_learning>0 && Days_passed>=Period_learning)
      enough_time=true;          //то тогда значение enough_time (достаточно времени) будет равно истине (true)
   return(enough_time);          //возвращаем значение "достаточно времени" в функцию "имею время"
  }
//--- Функция "имею_терпение"
bool have_patience()             //создаём функцию "имею_терпение" и присвоим тип данных bool
  {
   enough_patience=Patience;     //задаём для переменной enough_patience (достаточно терпения) значение равное
                                 //входному параметру "Терпение" (Patience): истина или ложь
   return(enough_patience);      //возвращаем значение "достаточно терпения" в функцию "имею терпение"
  }
//+------------------------------------------------------------------+
 
MrBrooklin:

Good day and good mood everyone!

I continue studying the MQL5 programming language. Taking into account the tips from Peter Konov, I am pasting the finalized code of the script that is a continuation of one of the tasks from the participants of this thread. The script has been tested in all modes. No problems detected. To begin with I applied the minimum number of input parameters. The script code is written in English, the comments to the code are in Russian, to ease the learning process. As I promised earlier, I tried to describe the script in a manner comprehensible to a pupil of the 1-st form of programming school.

Regards, Vladimir.

Fix one mistake on the fly and it will be perfect.

The point is that there is a structural error in function have_time(). Here is a hint:

If the body of a condition is not enclosed in curly brackets, the condition itself refers only to the first line following it. Since the body of your condition does not contain parentheses, the entry in the body of enough_time =true; is not related to the next following return-extension which will always return the last value of enough_time. So even if the condition is false but the variable has got the value true before, return will return true.

Think how to fix it.

P.S. Even though this is a script and it will work only once, there is still an error.

P.S.S. And also, global variables should be initialized with an initial value, and you have 2 variables not initialized. This is a "semi-error".
 
Реter Konow:
Fix one error and it will be perfect.

The point is that there is a structural error in have_time(). Here is a hint:

If the body of the condition is not enclosed in curly brackets, the condition itself is related only to the first line after it. Since the body of your condition does not contain parentheses, the entry in the body of enough_time =true; is not related to the next following return-extension which will always return the last value of enough_time. So even if the condition is false but the variable has got the value true before, return will return true.

Think how to fix it.

P.S. Even though this is a script and it will work only once, there is still an error.

P.S.S. And also, global variables should be initialized with an initial value, and you have 2 variables not initialized. This is a "semi-error".

Regarding the function, I assume this is how the code should have been written:

//--- Функция "имею_время"
bool have_time()                //создаём функцию "имею_время" и присвоим тип данных bool
  {
   /* Если:
      1. значение входного параметра Period_learning больше нуля
      2. и значение входного параметра Days_passed больше или равно значения входного параметра Period_learning
   */
   if(Period_learning>0 && Days_passed>=Period_learning)
     {
      enough_time=true;         //то значение enough_time (достаточно времени) будет равно истине (true)
     }
   else                         //в противном случае 
     {
      enough_time=false;        //значение enough_time (достаточно времени) будет равно ложь (false)
     }
   return(enough_time);         //возвращаем значение "достаточно времени" в функцию "имею время"
  }
Sincerely, Vladimir.
 
MrBrooklin:

About the function, I assume this is how the code should have been written:

Sincerely, Vladimir.
Right!
 
Реter Konow:
Just fix one error straight away and it will be perfect.

The point is that there is a structural error in have_time(). Here is a hint:

If the body of the condition is not enclosed in curly brackets, the condition itself is related only to the first line after it. Since the body of your condition does not contain parentheses, the entry in the body of enough_time =true; is not related to the return-it will always return the last value of enough_time. So even if the condition is false but the variable has got the value true before, return will return true.

Think how to fix it.

P.S. Even though this is a script and it will work only once, there is still an error.

P.S.S. And also, global variables should be initialized with an initial value, and you have 2 variables not initialized. This is a "semi-error".

Global objects, are initialized by default by constructor. For primitive (in our case, all but string) types it is 0. But for memory (read variables) allocated on the stack, they are not initialized. That's why global variables may be not initialized, remember that in this case they will equal zero. But absence of initialization (at the same time, get used to avoiding compiler-generated warnings right away, unless you know exactly what you're doing) is a serious issue, because reading an uninitialized variable leads to undefined behavior. For example, this code behaves differently in release and debug builds and no one can guarantee that when you change the compiler version or optimization settings its behavior will not change too:

int Test(bool condition,int in){
   int ret;
   if (condition) ret=in;
   return ret;
}

void OnStart()
{
   for(int i=0;i<5;Print(Test(false,i++)));
}
 
Реter Konow:

"...P.S.S. And also, global variables should be initialised with an initial value and you have 2 variables not initialised. This is a 'semi-error'..."

Peter, on the subject of global variables, I haven't yet found in the literature that global variables need to be predefined. Do you have a link to the source to improve your knowledge in this matter? The MQL5 Reference does not contain an explicit reference to initialization:

The booltype is designed to store the logical values true or false, whose numeric representation is 1 or 0 respectively .

Examples:

bool a =true;
bool b =false;
bool c =1;

The internal representation is a 1-byte integer number. It should be noted that in boolean expressions, it is acceptable to use other integer or real types or expressions of these types instead of bool, and the compiler will not generate an error. In this case, zero will be interpreted as false and all other values as true.

Sincerely, Vladimir.
 
Vladimir Simakov:

Global objects, are initialized with default constructor. For primitive (in our case, all except string) types, it is 0. But for memory (read variables) allocated on the stack, they are not initialized. That's why global variables may be not initialized, remember that in this case they will equal zero. But absence of initialization (at the same time, get used to avoiding compiler-generated warnings right away, unless you know exactly what you're doing) is a serious issue, because reading an uninitialized variable leads to undefined behavior. For example, this code behaves differently in release and debug builds and no one can guarantee that when you change the compiler version or optimization settings its behavior will not change too:

This is certainly informative, but global variables should be initialized explicitly for clarity. For example, in mql4 variables/arrays can be not initialized anywhere at all when being declared, and they still get initial zero. ))
Reason: