Difficulty: Easy · Puzzle 2 of 6 · Topic: Queue and Array Puzzles
After assignment and independent mutations, what are `q1` and `q2`?
module p2;
int q1[$] = '{1,2,3};
int q2[$];
initial begin
q2 = q1;
void'(q1.pop_front());
q2.push_back(4);
$display("q1=%p q2=%p", q1, q2);
end
endmoduleQueues are unpacked value types, not class handles.
1) `q2 = q1` copies queue contents into a separate queue.
2) `q1.pop_front()` changes only q1 to `{2,3}`.
3) `q2.push_back(4)` changes only q2 to `{1,2,3,4}`.Answer: q1=' {2,3}, q2=' {1,2,3,4}
Checked by running the code in Icarus Verilog 13 and Verilator 5; the printed output supports the answer above. Elements printed one by one because Icarus cannot print a whole queue with %p. The %p layout is tool-specific; the queue contents 2,3 and 1,2,3,4 are what matter.
`q2 = q1` copies the elements; a later `pop_front` on q1 does not touch q2, unlike a class handle assignment.
What collection type in SV would alias by handle instead of value? Model answer: none of the built-in containers does; only a class handle aliases, so a queue wrapped in a class object (or passed by `ref`) is shared by handle.
I would say that assigning a queue copies the elements, so the two queues are independent. After the pop front on the first queue it holds 2 and 3, and after the push back the second holds 1, 2, 3 and 4. The trap is thinking it behaves like a class handle, where both names would see the change. Only a class handle aliases, so I would check whether anything is wrapped in a class or passed by reference.