I understand the concept of local variable holding the value when loop unrolls with fork, join_none, but the position of where this variable is defined seems to give different results.
foreach(a[i]) begin
fork
int j=i;
a[j]=j;
$display("j is %d i is %d",j,i);
join_none
end
Here j takes value from 0 to 4 & i displays 5
foreach(a[i]) begin
fork
begin
int j=i;
a[j]=j;
$display("j is %d i is %d",j,i);
end
join_none
I assume this code is inside class methods, so all variable declarations have automatic lifetimes. Variables with automatic lifetimes initialize when procedural code enters the scope where the variable is declared.
In your first example, the declaration of int j is inside the fork/join_none block, but not part of any process being forked. You have 2 processes being forked each iteration. Every iteration has a local instance of j that gets initialized before any forked processes start.
In your second example, the the declaration of int j is inside the the begin/end block, which is the one process that is forked each iteration. The initialization of j does not happen until after the processes start, which is after the foreach loop has finished iterating.