Referencing structs in a foreach

Alf via Digitalmars-d digitalmars-d at puremagic.com
Tue Jul 22 18:31:46 PDT 2014


I am wondering what could be the mistake. When trying to modify 
the member of a struct from within a foreach, the changes are 
gone after leaving the loop.

Code:

import std.stdio;

void test()
{
   struct Foo
   {
     int a;
     int b;
   }

   struct Bar
   {
     Foo f1;
     Foo f2;
   }

   Bar bar = {{10, 20}, {10, 20}};

   writefln("Before => f1.a: %d, f1.b: %d - f2.a: %d, f2.b: %d\n", 
bar.f1.a, bar.f1.b, bar.f2.a, bar.f2.b);

   foreach (ref f; [bar.f1, bar.f2])
   {
     f.a++;
     f.b++;
   }

   writefln("After => f1.a: %d, f1.b: %d - f2.a: %d, f2.b: %d\n", 
bar.f1.a, bar.f1.b, bar.f2.a, bar.f2.b);
}

void main()
{
   test();
}

Should print:

Before => f1.a: 10, f1.b: 20 - f2.a: 10, f2.b: 20
After => f1.a: 11, f1.b: 21 - f2.a: 11, f2.b: 21

But prints:

Before => f1.a: 10, f1.b: 20 - f2.a: 10, f2.b: 20
After => f1.a: 10, f1.b: 20 - f2.a: 10, f2.b: 20

Thanks,

Alf


More information about the Digitalmars-d mailing list