Strange behavior using array of structures

Orfeo orfeo.davia at gmail.com
Wed Apr 4 10:00:18 UTC 2018


Hi all,
I have:

```
import std.stdio;

void main() {
    Logger[] log;
    Logger l0 = Logger(0,1);
    Logger l1 = Logger(100,1);
    Logger l2 = Logger(200,1);
    log ~= l0;
    log ~= l1;

    foreach (i; 0 .. 3) {
       writeln("it:", i);
       foreach (l; log) {
          l.run;
       }
    }
}

struct Logger {
    int initial;
    int increment;
    void run() {
       initial += increment;
       writeln("\t", initial);
    }
}
```
Output:
```
it:0
	1
	101
it:1
	1
	101
it:2
	1
	101
```
If I use:
```
void main() {
    Logger[] log;
    Logger l0 = Logger(0,1);
    Logger l1 = Logger(100,1);
    Logger l2 = Logger(200,1);
    log ~= l0;
    log ~= l1;
    foreach (i; 0 .. 3) {
       writeln("it:", i);
       l0.run();
       l1.run();
    }
}
```
output (correct) is:
```
it:0
	1
	101
it:1
	2
	102
it:2
	3
	103
```
can someone help me to understand? Thanks!




More information about the Digitalmars-d-learn mailing list