Verilog Tasks and Functions
As designs grow, you factor repeated behaviour into tasks and functions. They are Verilog’s subroutines — but the two differ in ways that matter for both simulation and synthesis.
| function | task | |
|---|---|---|
| Time / delays | none — executes in zero time | may contain #, @, wait |
| Returns | exactly one value | none (use output args) |
| Calls | only other functions | tasks or functions |
| Typical use | combinational helper | stimulus / multi-step sequence |
A function: pure, combinational, returns a value
module fn_demo;
function [3:0] bcd_inc (input [3:0] d); // returns one 4-bit value
bcd_inc = (d == 4'd9) ? 4'd0 : d + 4'd1;
endfunction
integer i; reg [3:0] v;
initial begin
v = 4'd7;
for (i = 0; i < 4; i = i + 1) begin
$display("v=%0d", v);
v = bcd_inc(v); // call like an expression
end
$finish;
end
endmodulev=7 v=8 v=9 v=0
A task: can consume time, drives outputs
module task_demo;
reg clk; reg [7:0] bus;
task send (input [7:0] data); // multi-step, time-consuming
begin
@(posedge clk) bus = data;
$display("t=%0t sent %0h", $time, bus);
end
endtask
always #5 clk = ~clk;
initial begin
clk = 0; bus = 0;
send(8'hA5);
send(8'h3C);
#3 $finish;
end
endmodulet=5 sent a5 t=15 sent 3c
Rule of thumb: if it needs a clock edge or a delay, it must be a task. If it is a one-shot combinational computation, make it a function — functions are synthesisable and keep combinational logic tidy.
▶ Try it in the ChipXpert Lab
Run both demos in the lab. Then try adding a #5 delay inside the function — the simulator will reject it, proving functions execute in zero time.
Check yourself
Can a function contain <code>@(posedge clk)</code>?
No. Functions must execute in zero simulation time and cannot contain timing controls (#, @, wait). Anything that waits for an event must be a task.
How does a task return results if it has no return value?
Through output (and inout) arguments in its port list. A task can produce several results this way, whereas a function returns exactly one value as its name.
Share your question in comments or talk to our mentor team for batch guidance.
Learn Verilog with mentors, labs and placement support
This free series is maintained by the ChipXpert training team in Hyderabad & Bengaluru. Go deeper with instructor-led courses on real EDA tools.
Explore VLSI Courses