Difficulty: Medium · Puzzle 5 of 6 · Topic: Parameterized Class Puzzles
Predict call counters after mixed static-method invocations across different POLY values.
class crc #(int POLY = 1);
static int calls = 0;
static function int calc(int x);
calls++;
return x ^ POLY;
endfunction
endclass
initial begin
void'(crc#(1)::calc(7));
void'(crc#(1)::calc(8));
void'(crc#(3)::calc(9));
$display("c1=%0d c3=%0d", crc#(1)::calls, crc#(3)::calls);
endStatic storage belongs to specialization, even for static methods.
1) Two calls are made on `crc#(1)` => `crc#(1)::calls` becomes 2.
2) One call is made on `crc#(3)` => `crc#(3)::calls` becomes 1.
3) No cross-specialization sharing occurs.Answer: Output is `c1=2 c3=1`.
Checked by running the code in Verilator 5; the printed output supports the answer above. The shown code run in Verilator: static methods and their counters are per specialization.
Static methods are often mistaken as globally shared across all parameter values.
How would you accumulate one global call count while still keeping per-POLY counts? Model answer: put a second static counter in a non-parameterized base class (or package) and increment both in `calc`; the base-class counter is shared by every `POLY`, while `calls` stays per specialization.
The output is c1 equals 2 and c3 equals 1. Each specialization has its own static calls counter, so two calls on the first specialization give 2, and one call on the other gives 1. The trap is assuming the counter is shared across parameter values, so I would check which specialization each call actually uses.