Conditional Statements

If Statements

An if statement evaluates an expression and executes the subsequent statement if the expression evaluates to true, otherwise it skips that statement. For example:

if (i > max_count)
    i = 0;

An if/else statement evaluates an expression and executes the statement before else if the expression evaluates to true, otherwise it evaluates the statement after the else. For example:

if (sel)
   out = in0;
else
   out = in1;

In particular, if sel is a single bit value, the if clause of the above example would be executed if sel were 1, and the else clause would be executed if sel were 0, x, or z.

A common idiom is to nest if/else statements as follows:

if (sel==0)
   out = in0;
else if (sel==1)
   out = in1;
else if (sel==2)
   out = in2;
else if (sel==3)
   out = in3;
else
   out = 'bx;

In this case an if keyword binds to the next closest else keyword.

Case Statements

A case statement tests and expression and then enumerates what actions should be taken for the various values that expression can take. For example:

case (sel)
   0: out = in0;
   1: out = in1;
   2: out = in2;
   3: out = in3;
endcase

Case statements test using the === operator, so if any of the bits in sel are x or z none of these cases will match and so the case statement will not execute any of its statements. You can associate multiple cases with a single statement by putting the cases in a comma separated list:

case (sel)
   2'b00: out = in0;
   2'b01: out = in1;
   2'b10: out = in2;
   2'b11: out = in3;
   2'bxx, 2'bx1, 2'b0x, 2'b1x: out = 'bx;
endcase

It is also possible to specify a default case:

case (sel)
   0: out = in0;
   1: out = in1;
   2: out = in2;
   3: out = in3;
   default: out = 'bx;
endcase

The are two special versions of the case statement available: casez and casex. casex treats an x or a z in either the case expression or the case items as don’t cares whereas casez only treats a z as a don’t care. In addition, ? in literal numbers are also treated as don’t cares:

always @result begin
   casex (result[3:0])
      4'b0000: $display("result is a multiple of sixteen.");
      4'b?000: $display("result is a multiple of eight.");
      4'b??00: $display("result is a multiple of four.");
      4'b???0: $display("result is even.");
      default: $display("result is odd.");
   endcase
end

This example also demonstrates another feature of case statements. Multiple cases may match. They are tried in the order that they are given and the first one that matches is used.