Variable Declaration

Variable Declaration

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.

Variables declaration

You can also declare many variables of the same type in a single line.

Single line declaration

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.

Variable Initialization

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.

Variable initialization

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.

New value assigned to already declared variable

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.

Declaration and initialization in a single line

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.  

About Lukas

Trader and programmer. Passionate about trading automation. Spent 5 years working in BNY Mellon, Citibank and MAN Investments. Currently self-employed in IT business. Has a stock broker license.

View all posts by Lukas →

Leave a Reply

Your email address will not be published. Required fields are marked *