{"id":96,"date":"2015-09-13T18:01:11","date_gmt":"2015-09-13T18:01:11","guid":{"rendered":"http:\/\/www.verilogpro.com\/?p=96"},"modified":"2022-06-27T00:43:12","modified_gmt":"2022-06-27T07:43:12","slug":"verilog-case-casez-casex","status":"publish","type":"post","link":"https:\/\/www.verilogpro.com\/verilog-case-casez-casex\/","title":{"rendered":"Verilog twins: case, casez, casex. Which Should I Use?"},"content":{"rendered":"\n

The Verilog case<\/b> statement is a convenient structure to code various logic like decoders, encoders, onehot state machines. Verilog defines three versions of the case statement: case<\/b>, casez<\/b>, casex<\/b>. Not only is it easy to confuse them, but there are subtleties between them that can trip up even experienced coders. In this article I will highlight the identifying features of each of the twins, and discuss when each should be used.<\/p>\n\n\n\n

Basic Verilog Case Statement<\/h3>\n\n\n\n

Let’s start by reviewing the basic case<\/b> statement:<\/p>\n\n\n\n

case (case_expression) \/\/ case statement header\n  case_item_1 : begin\n    case_statement_1a;\n    case_statement_1b;\n  end\n  case_item_2 : case_statement_2;\n  default     : case_statement_default;\nendcase<\/pre>\n\n\n\n

A case statement has the following parts:<\/p>\n\n\n\n

  • Case statement header<\/i>—consists of the case<\/b>, casez<\/b>, or casex<\/b> keyword followed by case expression<\/i><\/li>
  • Case expression<\/i>—the expression in parentheses immediately following the case<\/b> keyword. Valid expressions include constants (e.g. 1’b1), an expression that evaluates to a constant, or a vector<\/li>
  • Case item<\/i>—the expression that is compared against the case expression<\/i>. Note that C-style break<\/b> is implied following each case item statement<\/i><\/li>
  • Case item statement<\/i>—one or more statements that is executed if the case item<\/i> matches the current case expression<\/i>. If more than one statement is required, they must be enclosed with begin…end<\/b><\/li>
  • Case default<\/i>—optional, but can include statements to be executed if none of the defined case items<\/i> match the current case expression<\/i><\/li><\/ul>\n\n\n\n