HDLbits
Start Practicing

Verilog Language/More Features

4-to-1 Mux with the Ternary Operator

medium
more-featuresternarymuxconditional-operator

The ternary (conditional) operator condition ? if_true : if_false can be nested to build multi-way selection logic in a single expression, without needing an always block at all. This is a common, compact way to write small muxes directly in a continuous assignment.

Build a circuit with a 2-bit select input sel, four data inputs a, b, c, d, and one output out. out should equal a, b, c, or d depending on whether sel is 0, 1, 2, or 3, respectively — implemented using only nested ternary operators (no always block, no case).

Interface

Signal Direction Width Description
sel input 2 Selects which data input to output
a input 1 Selected when sel == 0
b input 1 Selected when sel == 1
c input 1 Selected when sel == 2
d input 1 Selected when sel == 3
out output 1 Selected data input

Notes

  • sel[1] splits the choice into {a,b} vs {c,d}; sel[0] then picks within that pair.
  • One valid form: sel[1] ? (sel[0] ? d : c) : (sel[0] ? b : a).