Verilog Control Flow
If-Else Statement
Syntax:
if (expression)
statement;
else if (expression)
statement;
else
statement;
Key Rules
expression
must evaluate to a 1-bit result (0
,1
,x
,z
).- Execution is first true branch wins (checked top to bottom).
- If none match and no
else
, no action occurs.
Common Uses
- Combinational decision making inside
always @(*)
. - Priority logic (highest branch gets priority).
Guidelines
- Always use full coverage (
else
ordefault
) to avoid unintended latch inference. - Use
begin…end
for multiple statements. - Use
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
Case, Casez, Casex Statements
General Syntax:
case (expression)
value1: statement;
value2: statement;
...
default: statement;
endcase
Case
- Exact match (bit-by-bit, including
x/z
). - Good for one-hot encoding or multi-way decode.
Casez
- Treats Z and ? as don’t-cares.
- Useful for partial matches and encoders.
casez (opcode)
4'b1???: alu_op = ADD;
4'b01??: alu_op = SUB;
default: alu_op = NOP;
endcase
Casex
- Treats X, Z, and ? as don’t-cares.
- Risky → can mask real unknowns in simulation.
- Synthesis tools may treat it differently; use sparingly.
Guidelines
- Always include
default
to prevent latches. casez
is preferred overcasex
in synthesizable RTL.- Case statements are parallel (not priority) unless overlapping values are used.
For Loop Statement
Syntax:
for (init; condition; step) statement;
Rules
- All loop control variables must be declared (
integer i;
). - Loop unrolls during elaboration if bounds are static.
- Synthesizable only with constant bounds.
Example
integer i;
always @(*) begin
sum = 0;
for (i=0; i<8; i=i+1) begin
sum = sum + data[i];
end
end
Guidelines
- Use
for
loops to describe repeated hardware structures (not like software loops). - Avoid unbounded or runtime-dependent loops in RTL → not synthesizable.
- For simulation-only,
forever
andwhile
are also allowed.
Concept understood? Let's apply and learn for real