As a task for learning how to write functions in Verilog, I am trying to write a function that just counts the number of ones in a given vector:
module m ();
parameter n = 4;
function integer count_ones (input [n-1:0] a);
for (integer i = 0 ; i<n ; i=i+1)
begin
if (a[i] ==1'b1)begin
count_ones=count_ones+1;
end
end
endfunction
initial begin
reg [3:0] a = 4'b1;
integer result = count_ones (a);
$display("output is ", result);
end
endmodule
The result is displayed as x. So what is the error in this code ?