1
always @* begin
if (SEL == 3'b000)
    ALU_OUT = A + B;
if (SEL == 3'b001)
    ALU_OUT = A - B;
if (SEL == 3'b010)
    ALU_OUT = ~(A & B);
if (SEL == 3'b011);
    ALU_OUT = ~(A | B);
if (SEL == 3'b100)
    ALU_OUT = ~A;
if (SEL == 3'b101)
    ALU_OUT = A >> B;
else 
    ALU_OUT = 0;
end

The above is my code, currently for the ALU. I have to code for overflow, but the main problem is that nothing in the code works. I am not sure what I have to fix because the computer doesn't say there is any errors. But, I fail all the tests. All the results are 0.

toolic
  • 57,801
  • 17
  • 75
  • 117
YJunior
  • 35
  • 3
  • the operations are only defined for 6 out of 8 combinations which is why i put ALU_OUT = 0 for else – YJunior May 13 '21 at 13:11
  • there is a given test bench code, and so all i have to do is create a code for ALU. when i compile testbench and my code together and run it, I have passed 0 tests as in the code gave incorrect output, although it runs normally( There is no syntax error). – YJunior May 13 '21 at 13:26
  • i am not an expert but you can try replacing ALU_OUT = with ALU_OUT <= – Rsvay May 17 '21 at 11:14

1 Answers1

0

Your code has a logic mistake. You have 5 separate if statements, plus 1 if/else statement. You most likely meant to have a single cascading if/else if/ else statement. In order to avoid this type of a mistake, it is better to use a case statement:

always @* begin
    case (SEL)
        3'b000  : ALU_OUT = A + B;
        3'b001  : ALU_OUT = A - B;
        3'b010  : ALU_OUT = ~(A & B);
        3'b011  : ALU_OUT = ~(A | B);
        3'b100  : ALU_OUT = ~A;
        3'b101  : ALU_OUT = A >> B;
        default : ALU_OUT = 0;
    endcase
end

With the case statement, once SEL matches one of the case items, the case statement is exited immediately.

In your code, each if is evaluated, and the last one wins. For example, if SEL is 0, then ALU_OUT = A + B is executed. The simulator, also checks the remaining if statements. When it reaches if (SEL == 3'b101), that evaluates to false, which means the else statement is executed: ALU_OUT = 0. This is why you get 0. The else is executed for any value of SEL.

I posted a complete testbench on edaplayground demonstrating that the case statement works.

toolic
  • 57,801
  • 17
  • 75
  • 117