Skip to main content

Task and Function

· loading · loading · · ·
HDL Verilog HDL
Axolot Logic
Author
Axolot Logic
Digital Design Engineer
Table of Contents
Verilog HDL Series - This article is part of a series.
Part 13: This Article

πŸ”§ Task and Function in Verilog
#

Tasks and functions are used to avoid code repetition and to encapsulate reusable logic. They improve code readability and maintainability, especially in simulation and testbench designs.


πŸ“Œ task
#

Tasks are procedural blocks that can have:

  • Multiple inputs and outputs
  • Timing controls like #, @, wait
  • Can call other tasks or functions
  • Can be used to drive global variables (unless overridden by local declarations)
  • Cannot be used inside assign expressions

βœ… Example:
#

task convert;
  input  [7:0] adc_in;
  output [7:0] out;
  begin
    out = (9/5) * (adc_in + 32);
  end
endtask

πŸ”” Usage:
#

always @(adc_a) convert(adc_a, adc_a_conv);

πŸ“Œ function
#

Functions are pure logic blocks that:

  • Must execute in zero simulation time
  • Can only return one value
  • Cannot include delays (#, @, wait, posedge, etc.)
  • Can call other functions, but cannot call tasks
  • Can be used in expressions, such as inside assign

βœ… Example:
#

function [7:0] myfunction;
  input [3:0] a, b, c, d;
  begin
    myfunction = ((a + b) + (c - d));
  end
endfunction

πŸ”” Usage:
#

assign f = myfunction(a, b, c, d) ? e : 8'd0;

🧠 Comparison Table
#

Feature task function
Return value Via output ports (can be multiple) Single return value only
Timing control Allowed (e.g., #, @, wait) Not allowed
Expression use ❌ Cannot be used in expressions βœ… Can be used
Calls Can call other tasks/functions Can only call functions
Usage Complex sequences, simulations Combinational logic
Delays/events Allowed Forbidden

⚠️ Best Practices
#

  • Use task for time-dependent or procedural operations.
  • Use function for pure, combinational calculations.

Verilog HDL Series - This article is part of a series.
Part 13: This Article

Related

Blocking vs Non-Blocking Assignments
· loading · loading
HDL Verilog HDL
Command-Line Input
· loading · loading
HDL Verilog HDL
Compiler Directives & Macros
· loading · loading
HDL Verilog HDL
Hierarchical Reference
· loading · loading
HDL Verilog HDL
Module Definition, Usage, and Constructs
· loading · loading
HDL Verilog HDL
Namespaces
· loading · loading
HDL Verilog HDL