Skip to content

SystemVerilog Associative Arrays Cheatsheet

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());

Iterating over Associative Array

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

Associative Array Methods

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

/* delete index */
age.delete("Paul");

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

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

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