On 11/13/15 10:48 AM, Ish wrote:

foreach (i; 0..5) {
   immutable int j = i;
   etc.
}
I want each j to be assigned separate memory so that it can be passed to
a calle function and not overwritten by next value of i in foreach()??

This is not safe to do. What you are doing is passing a scope-allocated variable to a function, and then examining the variable after the scope has exited (and essentially deallocated the variable).

The reason it "changes" is because your dangling pointer to that data is now pointing at the newly allocated variable in the new loop scope.

I would expect this code to behave strangely, and possibly crash.

If you want a variable to exist beyond it's declared scope, you must allocate on the heap as Alex said.

-Steve

Reply via email to