Gotcha: The Behavior of Foreach Loop Variables Depends on How the Array Dimensions Are Specified

< 1 min reading

In SystemVerilog the foreach statement can be used to iterate over the elements of an array. Special attention should be payed to loop variables (SystemVerilog IEEE 1800-2012 LRM Chapter 12.7.3, page 281), as their behavior depends on how the array dimensions are specified at declaration.

For example:

module tb;
  byte my_array[4:0];

  initial begin
    automatic byte counter = 5;
      
    foreach(my_array[idx]) begin
      my_array[idx] = counter++;
    end
      
    for(int i = 0; i < $size(my_array); i++) begin
      $display("my_array[%0d]: %0d", i, my_array[i]);
    end
 end
endmodule

One common mistake is to consider that the content of my_array is:

my_array[0]: 5
my_array[1]: 6
my_array[2]: 7
my_array[3]: 8
my_array[4]: 9

Actually, because the size of my_array was declared as a range from 4 to 0, the foreach loop variable idx goes from 4 down to 0, and the content of my_array is:

my_array[0]: 9
my_array[1]: 8
my_array[2]: 7
my_array[3]: 6
my_array[4]: 5

That's all!

Comments

One Response

  1. Nice post, wish I had read this before spending ~2 hours wondering why my code wasnt working as expected :)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Subscribe to our newsletter

Do you want to be up to date with our latest articles?