Download MetaTrader 5

About the scope of variables in "for" loops

To add comments, please log in or register
Guillermo
108
Guillermo  
Hello,

It is not a critical issue, but I'm a bit concerned about the future mainteinance of my code, and one thing I noticed is different from other languages (such as C) is the following. I think an example will be the easiest way to explain myself:

Invalid MQL4 code:

void OnStart() {
    for (int i = 0; i < 10; i++) {
        Print("Hello");
    }
    
    for (int i = 0; i < 10; i++) { // Error (line 6): variable 'i' already defined
        Print("Good bye");
    }
}


However, the equivalent C code is valid:

#include <stdio.h>

int main() {
        for (int i = 0; i < 10; i++) {
                printf("Hello\n");
        }
        
        for (int i = 0; i < 10; i++) {
                printf("Good bye\n");
        }
        return 0;
}


My concern with this is whether this is a bug in the MQL4 compiler or if this is intended. I have searched through the docs and found this page: https://docs.mql4.com/basis/variables/variable_scope where it says: "A variable declared inside a block (part of code enclosed in curly brackets) belongs to the local scope.". So it seems it is intended to be this way.

However, the following code also fails to compile:

void OnStart() {
    for (int i = 0; i < 10; i++) {
        int a = 5;
        Print("Hello");    
    }
    
    for (i = 0; i < 10; i++) {
        int a = 7; // Error (line 8): variable 'a' already defined, despite being declared inside a different "block (part of code enclosed in curly braces)"
        Print("Good bye");
    }
}


As of now, I'm writing my code the following way:

void OnStart() {
    int i = 0;
    int a = 0;

    for (i = 0; i < 10; i++) {
	a = 5;
        Print("Hello");
    }
    
    for (i = 0; i < 10; i++) {
	a = 7;
        Print("Good bye");
    }
}


 
In my real life scenario, I have more variables (not necessarily integers) with the same name in various loops, and I keep the declaration of all of them outside any loop. I feel this makes my code harder to maintain.

My question is, is it safe (by safe I mean, random-unexpected-results-free) to declare variables in for loops statements (or within a for loop block) and then have other variables without declaration in other loops/blocks of code?

I hope my point is easy to understand, because english is not my mother tongue.

Cheers.

Ex Ovo Omnia
3317
Ex Ovo Omnia  

Add the below line to your code:

#property strict

Guillermo
108
Guillermo  
Thanks Ovo for such a fast and to the point answer.

I will re-write all my code using this, hopefully I manage to do so without introducing bugs! :)

Cheers.
To add comments, please log in or register