Electrical – Can a Verilog function return an array indexed from one to the value passed in as an input parameter

verilog

If an input parameter to a Verilog function is integer "lg" then can the function return an array of integers indexed from one to (lg)?

Best Answer

A Verilog function can only return a vector (aka packed array) of fixed length or a single bit. Verilog also has the limitation that any array must have a fixed dimentions. Verilog arrays can be a fixed width vector (accessible by via bit index, slice, or as a whole), fixed depth unpacked array of bits (accessible by index only), or fixed depth unpacked array of uniform fixed width vectors (aka 2D array or memory).

Assuming you know the max size of the array, you could create a function that returns a vector of ARRAY_SIZE*INDEX_WIDTH, then slice the vector (probably using the +: operator; see
Indexing vectors and arrays with +:
) and assign to an unpacked array.


FYI: SystemVerilog functions do support returning array (of multiple dimentions), but may simulators require to typedef the return type if it is unpacked. Arrays of unfixed dimensions are not synthesizable.

typedef int my_array [];  // unsized array (requires new[] before assigning)
//typedef int my_array [$]; // queue
//typedef int my_array [int]; // associative array
function my_array my_function(input int lg);
  // ... your code ...
endfunction