Menu
CoddyTech

Casex And Casez

Part of the Fundamentals section of Coddy's Verilog journey. Lesson 56 of 90.

Sometimes you only care about specific bits in a value, while other bits can be ignored. For example, in a priority encoder, you want to find the first 1 bit regardless of the other bits.

A regular case statement would require you to list every possible combination of the don't-care bits, which is impossible for wide buses.

casez and casex solve this problem by allowing you to mark certain bits as "don't care" using ?, z, or x.

Casez vs Casex vs Regular Case

StatementDon't-Care BitsBest For
caseNoneExact matching
casezz or ?Priority encoders (recommended)
casexx, z, or ?Avoid (hides bugs)
  • casez ignores bits that are z or ? (recommended)
  • casex also ignores x bits, which can hide simulation errors

Always use casez, not casex. casex is dangerous because it ignores x values (which often indicate uninitialized registers or simulation errors). casez is the safer alternative because it does not treat x as don't-care.

Example

casez (data)
  4'b???1: out = 0;   // Bit0 must be 1, others don't matter
  4'b??1?: out = 1;   // Bit1 must be 1, others don't matter
  4'b?1??: out = 2;   // Bit2 must be 1, others don't matter
  4'b1???: out = 3;   // Bit3 must be 1, others don't matter
endcase

The ? means "don't care". That bit can be 0, 1, or anything.

challenge icon

Challenge

What to do:

Add the missing casez statement to make this decoder work.

How it works:

  • input = 4'b???1 → out = 4'b0001
  • input = 4'b??1? → out = 4'b0010
  • input = 4'b?1?? → out = 4'b0100
  • input = 4'b1??? → out = 4'b1000
  • Default → out = 4'b0000

Try it yourself

module decoder (
  input [3:0] in,
  output reg [3:0] out
);
  
  always @(*) begin
    // TODO: Add casez statement
    // in = 4'b???1 -> out = 4'b0001
    // in = 4'b??1? -> out = 4'b0010
    // in = 4'b?1?? -> out = 4'b0100
    // in = 4'b1??? -> out = 4'b1000
    // default -> out = 4'b0000
  end
  
endmodule
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Online Verilog compiler