Variadic Functions in Verilog

Here’s a function that will take an arbitrary number of ints as arguments.

function automatic void sum(input int nums []);
    int total = 0;
    $display("nums: %p", nums);
    foreach (nums[i]) begin
        total += nums[i];
    end
    $display("total: %0d", total);
endfunction

Within the function, the type of nums is equivalent to int[]. We can call nums.size(), iterate over it with foreach, etc.

Variadic functions can be called in the usual way with individual arguments.

initial begin
    sum('{1, 2});
    sum('{1, 2, 3});
end

If you already have multiple arguments in an array, apply them to a variadic function using the syntax func(array) like this.

initial begin
    int nums[] = '{1, 2, 3, 4};
    sum(nums);
end

To run the program, compile and execute the SystemVerilog code using a simulator.

$ vcs -sverilog variadic_functions.sv -o variadic_functions
$ ./variadic_functions
nums: '{1, 2}
total: 3
nums: '{1, 2, 3}
total: 6
nums: '{1, 2, 3, 4}
total: 10

Another key aspect of functions in SystemVerilog is their ability to form tasks, which we’ll look at next.