0
0
Verilogprogramming~5 mins

Case statement for multiplexing in Verilog

Choose your learning style9 modes available
Introduction

A case statement helps choose one option from many based on a value. It makes selecting signals easy in hardware design.

When you want to select one input out of many to send to an output.
When building a simple digital switch that routes signals.
When you need clear, readable code to pick between multiple options.
When designing a multiplexer circuit in Verilog.
When you want to avoid many if-else statements for selection.
Syntax
Verilog
case (selector)
  value1: output = input1;
  value2: output = input2;
  ...
  default: output = default_value;
endcase

The selector is the signal that decides which input to pick.

Always include a default case to handle unexpected values.

Examples
Selects one of four inputs based on 2-bit selector sel.
Verilog
case (sel)
  2'b00: out = in0;
  2'b01: out = in1;
  2'b10: out = in2;
  2'b11: out = in3;
  default: out = 1'b0;
endcase
Uses a 3-bit control signal to pick data; defaults to zero if no match.
Verilog
case (control)
  3'd0: data_out = data0;
  3'd1: data_out = data1;
  3'd2: data_out = data2;
  default: data_out = 8'b00000000;
endcase
Sample Program

This is a 4-to-1 multiplexer using a case statement. The selector sel picks which input signal goes to the output out. The testbench changes sel and prints the output.

Verilog
module mux4to1(
  input wire [1:0] sel,
  input wire in0, in1, in2, in3,
  output reg out
);

  always @(*) begin
    case (sel)
      2'b00: out = in0;
      2'b01: out = in1;
      2'b10: out = in2;
      2'b11: out = in3;
      default: out = 1'b0;
    endcase
  end
endmodule

// Testbench
module testbench;
  reg [1:0] sel;
  reg in0, in1, in2, in3;
  wire out;

  mux4to1 mux(.sel(sel), .in0(in0), .in1(in1), .in2(in2), .in3(in3), .out(out));

  initial begin
    in0 = 0; in1 = 1; in2 = 0; in3 = 1;
    sel = 2'b00; #10 $display("sel=%b out=%b", sel, out);
    sel = 2'b01; #10 $display("sel=%b out=%b", sel, out);
    sel = 2'b10; #10 $display("sel=%b out=%b", sel, out);
    sel = 2'b11; #10 $display("sel=%b out=%b", sel, out);
  end
endmodule
OutputSuccess
Important Notes

Case statements in Verilog are great for multiplexers because they clearly show all options.

Remember to use always @(*) for combinational logic to avoid latches.

Including a default case prevents unintended behavior if the selector has an unexpected value.

Summary

Case statements help pick one input from many based on a selector.

They make multiplexer design simple and clear.

Always include a default case and use always @(*) for combinational logic.