SystemVerilog Reference

typedef enum and Its Methods

An enum gives names to a set of values. Its methods step through the names and print them.

Syntax

typedef enum logic [1:0] {IDLE, BUSY, DONE} state_t;
state_t s = IDLE;
s = s.next();        // BUSY
$display(s.name());  // "BUSY"

Rules

  • Names count up from 0 unless you give values.
  • first() and last() return the first and last names.
  • next() and prev() step through the names and wrap at the ends.
  • name() returns the name as a string. num() returns how many names there are.
  • Assigning a plain number needs a cast: s = state_t'(2);.
  • A cast does not check the value. Use $cast(s, n) when the number may be out of range.

Example

module tb;
  typedef enum logic [1:0] {IDLE, BUSY, DONE} state_t;
  state_t s;

  initial begin
    s = s.first();
    repeat (4) begin
      $display("%s = %0d", s.name(), s);
      s = s.next();
    end
    $display("count = %0d", s.num());
  end
endmodule
Output on Verilator 5.052
IDLE = 0
BUSY = 1
DONE = 2
IDLE = 0
count = 3

Run It in the Playground

Common Mistake

A base type too small for the names

typedef enum logic {A, B, C} t;   // error: C needs the value 2

One bit holds only 0 and 1. The third name needs the value 2, which does not fit.

Fix: Size the base type for the largest value: logic [1:0] for up to four names.

Learn It Properly

These lessons teach it step by step, with practice problems.

Standard

IEEE 1800-2023, 6.19.