A new instance of a variable?

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Nov 13 08:37:19 PST 2015


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


More information about the Digitalmars-d-learn mailing list