Map a 2-bit opcode to a 4-bit one-hot alu_op. This is a parallel decode task (exactly one output bit high).
Requirements
alu_decoderopcode[1:0]alu_op[3:0]Behaviour
opcode = 2'b00 → alu_op = 4'b0001opcode = 2'b01 → alu_op = 4'b0010opcode = 2'b10 → alu_op = 4'b0100opcode = 2'b11 → alu_op = 4'b1000alu_op = 4'b0000Syntax:
if (expression)
statement;
else if (expression)
statement;
else
statement;
Key Rules
expression must evaluate to a 1-bit result (0, 1, x, z).else, no action occurs.Common Uses
always @(*).Guidelines
else or default) to avoid unintended latch inference.begin…end for multiple statements.case for parallel decisions; if-else is better for priority logic.Example
always @(*) begin
if (sel == 2'b00) y = a;
else if (sel == 2'b01) y = b;
else if (sel == 2'b10) y = c;
else y = d; // avoids latch
end
General Syntax:
case (expression)
value1: statement;
value2: statement;
...
default: statement;
endcase
x/z).casez (opcode)
4'b1???: alu_op = ADD;
4'b01??: alu_op = SUB;
default: alu_op = NOP;
endcase
default to prevent latches.casez is preferred over casex in synthesizable RTL.Syntax:
for (init; condition; step) statement;
Rules
integer i;).Example
integer i;
always @(*) begin
sum = 0;
for (i=0; i<8; i=i+1) begin
sum = sum + data[i];
end
end
Guidelines
for loops to describe repeated hardware structures (not like software loops).forever and while are also allowed.