Functions, Tasks, and Scope
Factor calculations and test sequences without hiding dependencies or mixing RTL with timing controls.
Use a function to calculate a value
A function returns a value and runs without consuming simulation time. It fits repeated combinational calculations.
function automatic logic [7:0] saturating_add8(
input logic [7:0] a,
input logic [7:0] b
);
logic [8:0] wide_sum;
wide_sum = {1'b0, a} + {1'b0, b};
if (wide_sum[8])
return 8'hFF;
return wide_sum[7:0];
endfunctionThe automatic keyword gives each call its own storage. This is the safe behavior for a reentrant function or one called concurrently in a testbench. A function declared in a module is available there, while a package function can be shared.