SystemVerilog Associative Arrays


Operations you can perform on SystemVerilog Associative Arrays

All code is available on EDA Playground

Declaring Associative Arrays

  logic [7:0] aa[int]; // int index type
  integer age[string]; // string index type
  logic [7:0] aaw[*]; // wildcard index type

Initializing Associative Arrays

    // Example from LRM
    // If a default value is specified, then reading a nonexistent 
    // element shall yield the specified default value
    age = '{"Peter":20, "Paul":22, "Mary":23, "Ray":35, "Jerry":31, default:-1 };

    // This prints default value of -1, since index does not exist
    $display("John %0d", age["John"]);

Size of Associative Array

   // size() or num() can be used, they are the same
   $display("AA size %0d %0d", age.size(), age.num());

Associative Array Methods

    /* check if index exists */
    if (age.exists("Peter")) 
      $display("Peter's age %0d", age["Peter"]);

    /* delete index */

    /* first, last, next, prev */
    // `tag` will get the first index
    // `tag` behaves as an inout variable. If tag has a valid index
    // then will store the next index into `tag` and return 1.
    // If tag is the last index and you call on it, then a 0 is returned.;
    nx = tag;

    // Similar to first and next, you can also use `age.last` and `age.prev`
    ls = tag;
    pr = tag;

    // print saved tags
    $display("first=%s, next=%s, last=%s, prev=%s", fr, nx, ls, pr);

Iterating over Associative Array

    if (age.first(fr)) begin
          $display("%s = %0d", fr, age[fr]);