SystemVerilog Reference
Associative Arrays
An associative array stores values under keys. It holds only the entries you write.
Syntax
int mem [bit [31:0]]; // key type in the brackets
int age [string];
mem[32'h1000] = 5;
if (mem.exists(32'h1000)) ...Rules
- Writing to a new key creates the entry.
exists(k)tells you whether a key is present.- Reading a missing key returns the default value and creates nothing.
num()orsize()gives the number of entries.delete(k)removes one.first(k),next(k),prev(k)andlast(k)walk the keys in sorted order.foreachalso visits the keys in sorted order.
Example
module tb;
int mem [bit [15:0]];
initial begin
mem[16'h2000] = 7;
mem[16'h0010] = 3;
mem[16'h0F00] = 9;
$display("entries = %0d", mem.num());
foreach (mem[addr]) $display("mem[%h] = %0d", addr, mem[addr]);
$display("exists(0x0011) = %0d", mem.exists(16'h0011));
mem.delete(16'h0010);
$display("entries = %0d", mem.num());
end
endmoduleentries = 3
mem[0010] = 3
mem[0f00] = 9
mem[2000] = 7
exists(0x0011) = 0
entries = 2Common Mistake
Treating a missing key as stored data
data = mem[addr]; // never written: returns 0, with no errorA read of a missing key gives the default value. A memory model then returns 0 for an address nobody wrote.
Fix: Check mem.exists(addr) first, and report a read of an unwritten address.
Learn It Properly
These lessons teach it step by step, with practice problems.
Standard
IEEE 1800-2023, 7.8.