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

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++;
    for(int i = 0; i < $size(my_array); i++) begin
      $display("my_array[%0d]: %0d", i, my_array[i]);

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!


Rahul Ramaswami July 22nd, 2020 01:00:38

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

Leave a Comment:

Your comment will be visible after approval.

(will not be published)

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