Hi All,
Consider the following code
bit [1:0] assoc[int];
int i;
initial begin
assoc[3] = 1;
assoc[10] = 0;
assoc[1] = 2;
foreach(assoc[j])
$display("assoc['d%0d] is 'd%0d",j,assoc[j]);
end
I observe that foreach iterates through the indexes of int type index of assoc in ascending order
i.e 1 → 3 → 10
Is there a way to iterate through assoc in descending order ? i.e 10 → 3 → 1
I tried using
for( assoc.last(i) ; i < assoc.size() ; assoc.prev(i) )
$display("assoc['d%0d] is 'd%0d",i,assoc[i]);
However, this doesn’t compile. Any suggestions on how to make it work ?
My 2nd attempt worked but I am not sure why I don’t run into an infinite loop
void’( assoc.last(i) );
do begin
$display("assoc['d%0d] is 'd%0d",i,assoc[i]);
end while( assoc.prev(i) );
How does the while loop terminate ?
from the description of the prev() function from IEEE Std 1800-2023:
7.9.7 Prev()
The prev() function finds the largest index whose value is smaller than the given index argument. If there is a previous entry, the index variable is assigned the index of the previous entry, and the function returns 1.
Otherwise, the index is unchanged, and the function returns 0.
so when i is the smallest key in assoc the next call to assoc.prev(i) will return 0, and will result in the end of the loop.
A way to make it work with the for loop can be:
for( int tmp = assoc.last(i) ; tmp ; tmp = assoc.prev(i) )
$display("assoc['d%0d] is 'd%0d",i,assoc[i]);
1 Like