Menu
Coddy logo textTech

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.

<strong>casez</strong> and <strong>casex</strong> 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)
  • <strong>casez</strong> ignores bits that are z or ? (recommended)
  • <strong>casex</strong> also ignores x bits — which can hide simulation errors

Always use <strong>casez</strong>, not <strong>casex</strong>. casex was created first, but engineers realized it was dangerous because it ignores x values (which often indicate uninitialized registers or simulation errors). casez was introduced as a safer alternative.

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???1out = 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

Cheat sheet

casez allows pattern matching with don't-care bits using ? or z, useful for priority encoders where only specific bits matter.

StatementDon't-Care BitsNotes
caseNoneExact matching
casezz or ?Recommended
casexx, z, or ?Avoid — hides bugs

Always prefer casez over casex. casex ignores x values, which can mask uninitialized registers or simulation errors.

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
  default: out = 0;
endcase

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

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