Case statements

Case statements in SystemVerilog are used for creating multiway branches. They are similar to switch statements in other languages like C or Java. Case statements are an essential part of control flow in SystemVerilog, allowing us to execute different parts of the code depending on the value of an expression.

Basic Case Statements

The syntax for a basic case statement in SystemVerilog is as follows:

case (expression)
    value1: statement1;
    value2: statement2;
    default: statementDefault;
endcase

For example, let's say we have a 2-bit variable cmd and we want to execute different logic based on its value:

case (cmd)
    2'b00: $display("Command 00 received");
    2'b01: $display("Command 01 received");
    2'b10: $display("Command 10 received");
    2'b11: $display("Command 11 received");
    default: $display("Invalid command");
endcase

casez and casex

In SystemVerilog, there are two variations of case statements called Casez and Casex. These are used when you have don't care bits in your case item expressions.

casez statement treats the character 'z' or 'Z' as a don't care value and casex statement treats both 'z'/'Z' and 'x'/'X' as don't care values.

casez (cmd)
    2'b0?: $display("Command 0x received");
    2'b1?: $display("Command 1x received");
endcase

casex (cmd)
    2'b0?: $display("Command 0x or 0z received");
    2'b1?: $display("Command 1x or 1z received");
endcase

case Inside

SystemVerilog also offers case inside which allows us to use set membership for multiway branching. It is particularly useful when case items are not a single value, but a range of values.

case inside (cmd)
    {[2'b00, 2'b01]}: $display("Command 00 or 01 received");
    {[2'b10, 2'b11]}: $display("Command 10 or 11 received");
endcase

As you can see, case statements provide a powerful way to manage control flow in your SystemVerilog programs. They allow for much cleaner and more readable code than a long series of if-else statements.

Have a Question?

Feel free to ask your question in the comments below.

Please Login to ask a question.

Login Now