Structs in Verilog

Structs in Verilog

Our first program will introduce structs. Verilog does not have a direct equivalent to structs as in many high-level programming languages but supports user-defined types (typedef) for similar functionalities.

module Main;

  // Define a 'person' struct
  typedef struct {
    string name;
    int age;
  } person_t;

  // Define a function to create a new person
  function person_t newPerson(string name);
    person_t p;
    p.name = name;
    p.age = 42; // Assign a default value to age
    return p;
  endfunction

  initial begin
    // Create a new struct using the default values
    person_t p;
    p.name = "Bob";
    p.age = 20;
    $display("Name: %s, Age: %0d", p.name, p.age);

    // Initialize the struct with field names
    person_t q;
    q = person_t'{"Alice", 30};
    $display("Name: %s, Age: %0d", q.name, q.age);

    // Omitted fields default to the default values (In Verilog, default for string is "")
    person_t r;
    r = person_t'{"Fred", 0};
    $display("Name: %s, Age: %0d", r.name, r.age);

    // Use a function to encapsulate struct creation
    person_t sp = newPerson("Jon");
    $display("Name: %s, Age: %0d", sp.name, sp.age);

    // Create an anonymous struct
    typedef struct {
      string name;
      bit isGood;
    } dog_t;

    dog_t dog = dog_t'{"Rex", 1};
    $display("Name: %s, Is Good: %b", dog.name, dog.isGood);
  end

endmodule

To simulate the program, you can put the code in a file named main.sv and use a Verilog simulator such as ModelSim or Vivado.

$ vlog main.sv
$ vsim -c -do "run -all; exit" Main

This will produce output similar to:

# ** Note: Name: Bob, Age: 20
# ** Note: Name: Alice, Age: 30
# ** Note: Name: Fred, Age: 0
# ** Note: Name: Jon, Age: 42
# ** Note: Name: Rex, Is Good: 1

Now that we can create and use simple structs in Verilog, let’s explore more advanced features of the language.