system verilog 中case 用法
时间: 2025-05-20 10:46:48 浏览: 19
### SystemVerilog Case Statement Usage
In SystemVerilog, the `case` statement provides a way to implement multiple-way branching based on an expression's value. The syntax of the `case` statement allows specifying several possible values for this expression and executing different blocks of code depending on which one matches.
The general form of a `case` statement includes:
- A controlling expression within parentheses.
- One or more `case` items each consisting of a constant expression followed by a colon and statements to execute if the condition is met.
- An optional default branch specified using `default:` keyword that handles all other cases not explicitly listed.
#### Example 1: Basic Case Statement
Here’s how a simple case structure looks like in practice:
```systemverilog
module example_case (
input logic [2:0] sel,
output logic y
);
always_comb begin : proc_y
unique case (sel)
3'b000: y = 1'b0;
3'b001: y = 1'b1;
3'b010: y = ~y; // This assumes initial value set elsewhere
default: y = 1'bx; // For any unmatched inputs
endcase
end
endmodule
```
This demonstrates basic usage where specific conditions lead directly to assignments without further nesting[^1].
#### Example 2: Using Inside Always Block With Reg Type Variables
When implementing combinational logic inside an `always` block, variables should be declared as type `reg`. Blocking assignment (`=`) must be used instead of non-blocking (`<=`) because we want immediate evaluation during simulation rather than scheduling changes at the next time step[^3].
```systemverilog
module complex_case (
input wire clk,
input wire reset_n,
input wire [7:0] opcode,
output reg result_valid
);
always_ff @(posedge clk or negedge reset_n) begin : proc_result_valid
if (!reset_n) begin
result_valid <= 1'b0;
end else begin
case(opcode)
8'hFF: result_valid = 1'b1;
8'hAA: result_valid = ~(result_valid); // Toggle state
default: result_valid = 1'b0;
endcase
end
end
endmodule
```
Note here that even though `opcode` might represent wires outside this module, internal signals such as `result_valid` are defined as registers due to being assigned within procedural constructs.
阅读全文
相关推荐


















