Dlang Fails to Run Instance Variable Declaration Code: 2 4 6 8 or 2 2 2 2

Language:
- D Programming Language
- DMD64 D Compiler v2.073.2

Issue:
- D fails to run member variable declaration code.
- Variable declarations are not dependable.

Workaround:
- Members should be initialized at constructor.

import std.stdio;
class B{
    public int x;
}
class A {
    public B b = new B();
    this() {
        //b = new B(); // uncomment this line for different behavior.
        b.x += 2;
    }
}
void main(string[] args) {
    for (int i=0; i<4++i) {
        auto a = new A();
        writefln("%d", a.b.x);
    }
}

Output (when commented):
2
4
6
8

Output (when uncommented):
2
2
2
2

Published: Apr 5, 2017

No comments:

Post a Comment

Sign up for the JBA Newsletter. A few times per year I may sell or give away gadgets and other electronics By signing up you ensure getting notified in a timely manner. I do NOT send you emails that will waste your time. Thank you.

Home

Hi. My name is Jesse, and I'm a technology enthusiast. I play with technology and share what I find on this blog. If you have any questions then please use the contact form below. I'll get back to you as soon as I can.


Contact

Name

Email *

Message *