MQL4|Boolean Type (bool)

Purpose

The Boolean type (bool) is used to represent a state of either true or false. It is an essential data type in programming for determining whether specific conditions are met in control structures such as conditionals and loops.

Size

The size of the Boolean type is 4 bytes. This design is for the sake of memory efficiency in computers.

Value Range

The Boolean type has only two possible values: true or false. true means that a condition is met, and false means that a condition is not met.

Example of Use

Below is an example of how the Boolean type is used. This example checks whether the price is above the moving average (MA) and outputs a message based on the condition.

//MQL4
void OnTick() {
    double ma = iMA(NULL, 0, 14, 0, MODE_SMA, PRICE_CLOSE, 0);
    double price = Close[0];
    bool isAboveMA = price > ma;

    if (isAboveMA) {
        Print("The price is above the moving average.");
    } else {
        Print("The price is below the moving average.");
    }
}

In this code, the Boolean type is used in the following steps:

  1. The iMA function calculates the 14-period Simple Moving Average (SMA).
  2. The current price is obtained using Close[0].
  3. It determines whether the current price is above the moving average and stores the result in the Boolean variable isAboveMA.
  4. The if statement outputs the appropriate message based on the value of isAboveMA.

In this way, the Boolean type plays a crucial role in controlling the program’s flow. It is vital to effectively utilize the Boolean type when implementing conditional logic.