static variable initialization bug?

 

This code prints "0" though it should print "1".

struct X
{
        int N;
        X()
        {
                static int n = 1;
                Print(n);
        }
};
X x;

void OnStart()
{
}


This code prints "1".

struct X
{
        int N;
        X()
        {
                static int n = 1;
                Print(n);
        }
};

void OnStart()
{
        X x;
}
 
minimax2000:

This code prints "0" though it should print "1".

This code prints "1".

How To Ask Questions The Smart Way. 2004
          Don't rush to claim that you have found a bug.
Questions Not To Ask
          My program doesn't work. I think system facility X is broken.

The order of initialization of global and static variables (X and n) are not defined. (Other than before OnInit.) It could print “1”, there is no should.

That is not an assignment; it's initialization of a common (globally declared,) or static variable with a constant. They work exactly the same way in MT4/MT5/C/C++.

  1. They are initialized once on program load.

  2. They don't update unless you assign to them.

  3. In C/C++ you can only initialize them with constants, and they default to zero. In MTx you should only initialize them with constants. There is no default in MT5, or MT4 with strict (which you should always use).

    MT4/MT5 actually compiles with non-constants, but the order that they are initialized is unspecified and

    Don't try to use any price or server related functions in OnInit (or on load,) as there may be no connection/chart yet:

    1. Terminal starts.
    2. Indicators/EAs are loaded. Static and globally declared variables are initialized. (Do not depend on a specific order.)
    3. OnInit is called.
    4. For indicators OnCalculate is called with any existing history.
    5. Human may have to enter password, connection to server begins.
    6. New history is received, OnCalculate called again.
    7. New tick is received, OnCalculate/OnTick is called. Now TickValue, TimeCurrent, account information and prices are valid.

  4. Unlike indicators, EAs are not reloaded on chart change so you must reinitialize them, if necessary.
              external static variable - MQL4 programming forum #2 2013.02.10

 

I didn't know the order of initialization is unspecified.

Thank you very much for your detailed answer, William.