Functions in Verilog

Functions are central in Verilog. We’ll learn about functions (also known as tasks and functions in Verilog) with a few different examples.

module functions;

  // Here's a function that takes two inputs and returns their sum
  function integer plus;
    input integer a, b;
    begin
      plus = a + b;
    end
  endfunction

  // In Verilog, we can define tasks for operations that don't return a value
  // This is similar to the plusPlus function in the original example
  task plusPlus;
    input integer a, b, c;
    output integer result;
    begin
      result = a + b + c;
    end
  endtask

  // The main block in Verilog is typically an initial block
  initial begin
    integer res;

    // Call a function just as you'd expect
    res = plus(1, 2);
    $display("1+2 = %d", res);

    // Call a task
    plusPlus(1, 2, 3, res);
    $display("1+2+3 = %d", res);
  end

endmodule

In Verilog, we use function for operations that return a value and task for operations that don’t return a value. The initial block is used to simulate the main function behavior.

To run this Verilog code, you would typically use a Verilog simulator. The equivalent of running the code would look something like this:

$ iverilog -o functions functions.v
$ vvp functions
1+2 = 3
1+2+3 = 6

This assumes you’re using the Icarus Verilog compiler (iverilog) and simulator (vvp).

There are several other features to Verilog functions and tasks. One is the ability to have multiple output parameters in tasks, which is similar to multiple return values in some programming languages.