Case Statement - Verilog Example

The Verilog Case Statement works exactly the way that a switch statement in C works. Given an input, the statement looks at each possible condition to find one that the input signal satisfies. They are useful to check one input signal against many combinations.

Just like in C, the VHDL designer should always specify a default condition provided that none of the case statements are chosen. This is done via the "default: " statement. See the example below.

One thing to note with case statements is that Verilog does not allow the use of less than or greater than relational operators in the test condition. Only values that are equal to the signal in the case test can be used.

Note that the example below uses the brackets for concatenation.

A note about synthesis: When case statements are synthesized by the tools, they generate optimized decode logic to quickly select which case statement is valid. They are more efficient than using if/else statements because if/else can generate long carry-chains of logic that can cause difficulties meeting timing.

example_case_statement.v:

module case_statement ();

  reg r_VAL_1 = 1'b0;
  reg r_VAL_2 = 1'b0;
  reg r_VAL_3 = 1'b0;
  
  reg [3:0] r_RESULT = 4'b0000;

  // Uses r_VAL_1, r_VAL_2, and r_VAL_3 together to drive a case statement
  // This always block is synthesizable
  always @(*)
  begin
    case ({r_VAL_1, r_VAL_2, r_VAL_3})
      3'b000  : r_RESULT <= 0;
      3'b001  : r_RESULT <= 1;
      3'b010  : r_RESULT <= 2;
      default : r_RESULT <= 9; 
    endcase
  end

  // *Initial* is never synthesizable.  Test code only!
  initial begin 
    r_VAL_1 <= 1'b0;
    r_VAL_2 <= 1'b0;
    r_VAL_3 <= 1'b0;
    #100;
    r_VAL_2 <= 1'b0;
    r_VAL_3 <= 1'b1;
    #100;
    r_VAL_2 <= 1'b1;
    r_VAL_3 <= 1'b0;
    #100;
    r_VAL_2 <= 1'b1;
    r_VAL_3 <= 1'b1;
    #100;
    #1000000;
  end
  
endmodule // case_statement


Modelsim simulation wave output

Help Me Make Great Content!     Support me on Patreon!     Buy a Go Board!