Why find_first_index/find_last_index functions return array?

The find_first_index and find_last_index return an array consisting of one element indicating position if the element is present else an empty array.

They could have returned -1 if found, else position.

If one wants to use the above array locator method, he/she needs to do the following:


int q[$];
int num;
int result[$];
.
.
.
result = (q.find_last_index with (item == num));
if(result.size() == 0)


If the following one liner is used, compilation error is thrown (with the obvious long line of code):


if((q.find_last_index with (item == num)).size() == 0)

In reply to prashantg:

All of the find methods return an array because the source array could be empty. Returning -1 is not an option because that is a potential valid index.

In reply to dave_59:

Dave, can you please provide an example where negative indexes are used to index an array. Example “-1” as an index.

In reply to yourcheers:
https://www.google.com/search?client=safari&rls=en&q=examples+of+arrays+with+negative+index&ie=UTF-8&oe=UTF-8

(Note, Verilog supported negative indexes long before Python was invented)

In reply to dave_59:

unlike python I assume we need to explicitly declare the range to have negative numbers in verilog.


module test;
  int a[8:-1];
    initial begin
      a = '{1,2,3,4,5,6,7,8,9,10};
      $display(a[-1]);
    end
endmodule

In reply to yourcheers:

yes… in Verilog it is required to declare negative index. And it is interpretation is different for Verilog and Python.

IEEE Standard for Verilog® Hardware Description Language
6.9.1 Specifying vectors
The range specification ([msb_constant_expression : lsb_constant_expression]) gives addresses to the
individual bits in a multibit reg, logic, or bit vector. The most significant bit, specified by the msb
constant expression, is the left-hand value in the range, and the least significant bit, specified by the lsb
constant expression, is the right-hand value in the range.
Both the msb constant expression and the lsb constant expression shall be constant integer expressions. The
msb and lsb constant expressions (see 11.2.1) may be any integer value—positive, negative, or zero. It shall
be illegal for them to contain any unknown (x) or high-impedance bits. The lsb value may be greater than,
equal to, or less than the msb value.

In reply to Alokpati:

Yes, switching back and forth from python range indexing to Verilog range indexing it quite a challenge.