Search code examples
verilogsystem-verilog

Why is this counter assignment wrong?


I am learning Verilog using the HDLBits website, and I solved this problem (circuit counts the number of '1's in an input vector), but I want to understand why my previous tries were wrong.

correct answer

module top_module( 
    input [254:0] in,
    output [7:0] out );
    
    int i ;
    reg [7:0] counter;
    
    always @(*) begin 
        counter =0;
        for (i=0;i<255;i++)begin 
            counter = (in[i]==1)? counter+1:counter;
        end 
    out = counter ;
    end 
   

endmodule

1st wrong answer

module top_module( 
    input [254:0] in,
    output [7:0] out );
    
    int i ;
    reg [7:0] counter;
    
    always @(*) begin 
        counter =0;
        for (i=0;i<255;i++)begin 
            counter = (in[i]==1)? counter+1:counter;
        end 
    end 
    out = counter ;

endmodule

2nd wrong answer

module top_module( 
    input [254:0] in,
    output [7:0] out );
    
    int i ;
    
    
    always @(*) begin 
        out=0;
        for (i=0;i<255;i++)begin 
            out = (in[i]==1)? out+1:out;
        end 
    end 
    

endmodule

Solution

  • All 3 code samples have syntax errors. If the HDLBits website did not report errors, try the EDA Playground website simulators.

    In your "correct" answer you need to change

    output [7:0] out );
    

    to:

    output reg [7:0] out );
    

    When you make an assignment to a signal inside an always block (a procedural assignment), you need to declare the signal as a reg.

    In your "1st wrong answer", change:

    out = counter ;
    

    to:

    assign out = counter ;
    

    Continuous assignments (outside of always blocks) require the assign keyword.

    In your "2nd wrong answer", use reg for out.