What is the output of this Verilog testbench code when run?
module test; reg [3:0] a, b; initial begin a = 4'd5; b = 4'd3; add_and_display(a, b); end task add_and_display(input [3:0] x, input [3:0] y); reg [4:0] sum; begin sum = x + y; $display("Sum is: %d", sum); end endtask endmodule
Remember that the task adds two 4-bit numbers and displays the result as a decimal.
The task adds the two inputs 5 and 3, resulting in 8, and displays it.
What value does the function multiply_by_two return in this testbench?
module test; reg [3:0] val; reg [4:0] result; initial begin val = 4'd7; result = multiply_by_two(val); $display("Result: %d", result); end function [4:0] multiply_by_two(input [3:0] x); begin multiply_by_two = x << 1; end endfunction endmodule
Left shift by 1 is the same as multiplying by 2.
The function shifts 7 left by 1 bit, which equals 14.
What will be the order and timing of the outputs when this testbench runs?
module test;
initial begin
$timeformat(-9, 1, " ns", 6);
display_message();
end
task display_message;
begin
$display("Start time: %t", $time);
#5;
$display("After 5 time units: %t", $time);
#10;
$display("After 15 time units: %t", $time);
end
endtask
endmoduleDelays inside a task add to the simulation time sequentially.
The task prints at time 0, then waits 5 units, prints, waits 10 more units, then prints again.
What is the output of this testbench code?
module test; reg [3:0] val; reg [3:0] res; initial begin val = 4'd9; res = check_and_double(val); $display("Result: %d", res); end function [3:0] check_and_double(input [3:0] x); begin if (x > 8) check_and_double = x * 2; else check_and_double = x; end endfunction endmodule
Remember the function returns a 4-bit value, so multiplication may overflow.
9 * 2 = 18 decimal, which is 10010 binary. Only 4 bits are stored, so lower 4 bits are 0010 (2 decimal).
What is the value of out_val after this testbench runs?
module test; reg [3:0] in_val, out_val; initial begin in_val = 4'd7; out_val = 4'd0; modify_values(in_val, out_val); $display("out_val: %d", out_val); end task modify_values(input [3:0] in_val, output [3:0] out_val); begin out_val = in_val + 3; end endtask endmodule
Output ports in tasks can modify variables passed by reference.
The task adds 3 to in_val (7), so out_val becomes 10.
