In MQL4 before we use any variable in the code, we need to first declare it. Declaration is simply giving variable a name and a type. Two parameters that will stay the same within our program. You can always assign a new value to a variable, but you can’t change their name and type once they are declare.
How to Declare a Variable
First, we write a data type, for example int then a name, and at the end we put a semicolon. Semicolon is very import; each line of code must end up with semicolon. This way the complier knows that it can move to the next line. Below samples of variable declarations of different data type.
You can also declare many variables of the same type in a single line.
We just declared 6 different variables of the int type. Remember that MQL4 is case sensitive. So last three variables are considered different ones.
In relation to names of variable, you can use letters, digits and underscores but the name of a variable must start with a letter.
You might now be wondering what are values of such variables? The answer is they are zero or null in the string case. We can say that they are like empty boxes waiting to be filled with something. So, to fill them with some value we need to initialize them.
Initialization is assigning a value to a variable for the first time. To do it, simply write an already declared variable name, equal sign, value and a semicolon. Let’s initialized previously declared variables.
All of them are now initialized – meaning they have value assigned to them. Later in the code we can assign a new value to any of them in the exact way. We will simply write the name of a variable and give it a new value.
Remember that you can declare and initialize a variable in one line. Let’s declare a variable “Subject” of string type with the value “Number of orders” and a variable named A, of int type with a value 10.
We just declared and initialized two variables in single lines.
They way how we do it depends on the type of program we are creating. But both ways give us the same results.
That is really it – all you need to know about variable declaration and initialization.