SourceRTL Design Directory

Case Statement: An Overview

The case statement is a fundamental construct in any programming language. The case statement selects one of many outputs based on the value of the case expression. It is equicalent to an if-else-if statement.

Syntax

case(case expression)
  case item1 : case statement_1;
  case item2 : case statement_2;
  case item3 : case statement_3;
  ...
  default : case statement_default;
endcase
  • Case Expression: The case statement chooses the case item based on the case expression.
  • Case Item: Case item is an expression, bit or a vector. When the case expression matches the case item, case statement will be executed.
  • Case Statement: Case item is single or a block of code that will be execute when the case item matched the case expression.
  • Default Case: The default case is optional but recommend to hancdle any values that do not match the specified case item.

Case Variants

There are two case variants for called casex and casez more flexible case item matching.

Casex

The casex statement allows for “don’t care” conditions by treating all ‘z’, ‘?’, and ‘x’ values as wildcards. This means that any bit in the case expression or case item that is ‘z’, ‘?’ or ‘x’ will match any corresponding bit in the case expression.

Casez

The casez statement is similar to casex, but it only treats ‘z’ and ‘?’ values as don’t cares. Unknown (x) values are treated as specific values and must match exactly. Casez particularly beneficial when the case expression or case statement is derived from an external source, where ‘x’ values are considered as “don’t care” conditions. However, it is important to recognize that these ‘x’ values may actually represent undesirable states. Such a misinterpretation can lead to unintended case statement evaluations, and erroneous circuit designs.

Points to Remember

  1. Always use casez when don’t cares are involved.
  2. Avoid using casex for synthesizable code.
  3. Casex treats ‘x’ and ‘z’ as dc.
  4. Casez treats ‘z’ as dc.
  5. In verilog, ‘?’ is an alias for ‘z’ in numerical literals.

Reference

  1. “full_case parallel_case”, the Evil Twins of Verilog Synthesis