Gaurav Gupte
Gaurav Gupte

Reputation: 141

case statement with multiple cases doing same operation

I need to use a case statement with the control signal being 4 bits. I have multiple cases of those 4 bits doing the same operation, how do I make the code more concise?

For ex:

  casez (fbe)  //fbe is defined as logic [3:0] fbe;
   4'b0000: begin
    // operation a
   end
   4'b???1 : begin
    // operation b
   end

Operation a and operation b are exactly identical. How do I collapse these 2 into a single case? Something like (fbe == 4'b0000) | (fbe == 4'b???1) into a single case?

Upvotes: 10

Views: 60669

Answers (2)

Greg
Greg

Reputation: 19122

You can use commas to separate all case expressions that will perform the operations. The default condition cannot be in this list (because it would be redundant).

Example:

casez(fbe)
  4'b0000, 4'b???1 : begin /* do same stuff */ end
  4'b??10 : begin /* do other stuff */ end
  default : begin ... end
endcase

This is documented in IEEE Verilog and SystemVerilog LRMs with examples. Such as IEEE1364-1995 § 9.5 Case statement and IEEE1800-2012 § 12.5 Case statement.

Upvotes: 19

dave_59
dave_59

Reputation: 42788

In SystemVerilog, you should use the case (expression) inside statement. (§12.5.4 Set membership case statement). This lets you use the same kind of lists of expressions that the inside operator uses, like a range of values. It also has asymmetrical wildcard matching. This means only Z's in the case item become wildcards, not Z's in the case expression. For example

case (fbe) inside
  4'b0000, 4'b0??1: begin end // 0, and 1,3,7
  [9:11]: begin end // 9,10,11
  default: begin end //2,4,6,8,12-15
endcase

If fbe was 4'bz000 for some reason, the default would be taken. casez would have matched 4'b0000.

Upvotes: 8

Related Questions