Verilog "Case" Statement

September 28, 2015


If you have already read all the papers from this website Sunburst Design, you probably already know how the case statement in Verilog is synthesized. I was asked several times during interviews for the use of the "case" statement. Let me summarize this statement here in this article now.


First of all, the following 3 pieces of codes are identical after synthesis.

  • Style 1 uses "case" statement:

case(STATE)

2'b00: c = a;

2'b01: c = ~a;

default: c = 1'b0;

endcase

  • Style 2 uses "if ... else ..." statement:

if (STATE=2'b00)

c = a;

else if (STATE=2'b01)

c = ~a;

else c = 1'b0;

  • Style 3 uses assignment directly:

c = (STATE=2'b00) ? a: (STATE=2'b01) ? ~a:1'b0;

Personally, I would prefer Style 3 since it requires the least number of code lines, but there is really no difference after synthesis: the synthesis tool will probably transfer all of them into some priority-encoded combinational logic. If I were an interviewer, I would ask you questions like this: In Moore machine, the outputs generated are determined by the status of the state machine. Suppose the state machine is one-hot encoded: SLEEP, WAKEUP, and IDLE. I want you to generate an output "c": The value of "c" depends on the states I just introduced. That is, if the current state ("STATE") is SLEEP, then c = 2'b00. If the current state is WAKEUP, then c = 2'b01; if the current state is IDLE, then c = 2'b10. I ask you not to have the priority encoder but to have a parallel structure that checks all the conditions at the same time, how do you write the code?


With the "case" statement, we can achieve this goal. There are too many wrong answers, but I will just introduce the right one here to avoid confusion. Please note that you should never forget the default case (you know why):

PARAMETER SLEEP=0;

PARAMETER WAKEUP=1;

PARAMETER IDLE=2;

case(1'b1)

STATE[SLEEP]: c = 2'b00;

STATE[WAKEUP]: c= 2'b01;

STATE[IDLE]: c= 2'b10;

default: c = 2'b11;

endcase

Sunburst Design has introduced the reasons why this works. In my opinion, this design style should be kept as a golden one that any hardware engineers should always follow. In other words, "don't ask why but just follow it".