Prev Problem
Next Problem

63. Functions and Tasks Basics

Question.3

What are the properly assigned hexadecimal values for a and b?

task split_byte(input [7:0] in_bus, output [3:0] hi, output [3:0] lo);
    begin
        hi = in_bus[7:4];
        lo = in_bus[3:0];
    end
endtask

reg [3:0] a, b;
initial begin
    split_byte(8'hC4, b, a);
end

 

Need Help? Refer to the Quick Guide below

Function

  • Purpose: Pure combinational calculations.
  • Return: Exactly one value.
  • Timing controls: Not allowed (#, @, wait).
  • Inputs: Passed by value only (cannot be output or inout).
  • Side effects: No global variable updates, only local/internal.

Syntax

function [WIDTH-1:0] func_name;
  input [WIDTH-1:0] a, b;  // inputs only
  begin
    func_name = a + b;      // return value
  end
endfunction

Usage

assign y = func_name(x, z);  // can be used inside expressions

Task

  • Purpose: Flexible procedure — useful for testbenches or complex modeling.
  • Return: Can modify multiple outputs.
  • Timing controls: Allowed (#, @, wait).
  • Inputs/Outputs: input, output, inout supported.
  • Side effects: Can update global variables and interact with simulation.

Syntax

task task_name;
  input  [7:0] a, b;
  output [7:0] sum, diff;
  begin
    sum  = a + b;
    diff = a - b;
  end
endtask

Usage

task_name(x, y, s, d);  // call by name

Function vs Task

FeatureFunctionTask
Return valuesOne (function name)Many (via output/inout)
Timing controls❌ Not allowed✅ Allowed
Global side effects❌ Not allowed✅ Allowed
Usage in expressions✅ Yes (part of continuous/procedural)❌ No (must be called as a statement)
Synthesis useCombinational logicTestbenches, complex procedures

Quick mnemonic: Use a function when you need a “calculator” (pure math, single return). Use a task when you need a “procedure” (multi-output, delays, events, or side effects).

Select Answer

Restart quiz!